diff --git a/Cargo.lock b/Cargo.lock index cb0c72cc0c..0d32cc52e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1044,6 +1044,20 @@ name = "craft-eps" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +[[package]] +name = "craft-font-catalog" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" +dependencies = [ + "harfrust 0.13.3", + "kurbo 0.13.1", + "skrifa 0.47.0", + "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", + "windows-registry", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -6630,6 +6644,7 @@ dependencies = [ "webbrowser", "windows", "winit", + "winreg", "winresource", "winsafe", "wl-clipboard-rs", @@ -7109,6 +7124,7 @@ dependencies = [ name = "vectorcraft-text" version = "0.24.1" dependencies = [ + "craft-font-catalog", "craft-proof", "harfrust 0.13.3", "icu_segmenter", diff --git a/ROADMAP.md b/ROADMAP.md index 236fc185eb..ea37f12caf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -157,6 +157,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 9a1b11e350..58b9741ac5 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -40,6 +40,9 @@ craft-print = { workspace = true } [target.'cfg(windows)'.dependencies] craft-update = { workspace = true } clipboard-win = { workspace = true } +# Reads a print queue's Standard TCP/IP RAW port for the direct-PDF transport (src/direct_pdf.rs). +# MIT, already in the build through the update client. +winreg = "0.55" # Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the # GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over # Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter. diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index db3518c26e..a5d450b854 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -3,6 +3,8 @@ use std::process::Command; use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; +mod direct_pdf; + pub struct SystemPrint; impl PrintService for SystemPrint { fn printers(&mut self) -> Vec { @@ -43,6 +45,9 @@ mod system { craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect() } pub fn print(job: &PrintJob) -> Result { + if job.direct_pdf { + return super::direct_pdf::print(job); + } // Copies, layout, marks and colour management are already in the PDF. Preserve its // physical sheet size and the queue's duplex default without printing copies twice. let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; diff --git a/apps/vectorcraft/src/printing/direct_pdf.rs b/apps/vectorcraft/src/printing/direct_pdf.rs new file mode 100644 index 0000000000..93e657cce9 --- /dev/null +++ b/apps/vectorcraft/src/printing/direct_pdf.rs @@ -0,0 +1,127 @@ +//! Send the print-ready PDF to the printer's own PDF interpreter over its RAW TCP port. +//! +//! This is the opt-in escape hatch for large-format PCL drivers that rewrite a custom page +//! (the HP DesignJet Z5200ps V4 driver emits a square PCL page for a 1067 x 480 mm sheet). The +//! PDF already carries the paper size, so the printer's interpreter prints it as laid out. + +#[cfg(windows)] +mod imp { + use std::io::Write; + use std::net::{Shutdown, TcpStream, ToSocketAddrs}; + use std::time::Duration; + + use vectorcraft_ui_egui::print::PrintJob; + use winreg::RegKey; + use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ}; + + /// Submit one composed PDF to the selected printer's Standard TCP/IP RAW port. + pub fn print(job: &PrintJob) -> Result { + let printer = job + .printer + .map(str::to_string) + .or_else(|| craft_print::printers().into_iter().find(|p| p.default).map(|p| p.name)) + .ok_or("direct PDF needs a selected printer")?; + let (host, port) = tcp_port(&printer)?; + send(&host, port, &pjl(job.title, job.pdf))?; + Ok(format!(" (direct PDF to {host}:{port})")) + } + + /// The `HostName` and port of a printer port registered as a Standard TCP/IP RAW port. + fn tcp_port(printer: &str) -> Result<(String, u16), String> { + let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); + let printer_key = hklm + .open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Printers\{printer}"), KEY_READ) + .map_err(|e| format!("direct PDF: cannot read the printer settings for {printer}: {e}"))?; + let port_name: String = printer_key.get_value("Port").map_err(|e| format!("direct PDF: {printer} has no port: {e}"))?; + let port_key = hklm + .open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\{port_name}"), KEY_READ) + .map_err(|e| format!("direct PDF: {printer} does not use a Standard TCP/IP port ({port_name}): {e}"))?; + let protocol: u32 = port_key.get_value("Protocol").unwrap_or(1); + if protocol != 1 { + return Err(format!("direct PDF: {printer}'s port ({port_name}) is not a RAW TCP/IP port")); + } + let host = port_key + .get_value::("HostName") + .ok() + .filter(|h| !h.trim().is_empty()) + .or_else(|| port_key.get_value::("IPAddress").ok().filter(|h| !h.trim().is_empty())) + .ok_or_else(|| format!("direct PDF: {printer}'s port ({port_name}) has no host address"))?; + let number = port_key.get_value::("PortNumber").unwrap_or(9100); + let port = u16::try_from(number).map_err(|_| format!("direct PDF: invalid port number {number}"))?; + Ok((host.trim().to_string(), port)) + } + + /// Frame the PDF for the printer's PJL interpreter. + fn pjl(title: &str, pdf: &[u8]) -> Vec { + let mut name: String = title.chars().map(|c| if (c.is_ascii_graphic() || c == ' ') && c != '"' { c } else { '_' }).take(80).collect(); + if name.is_empty() { + name.push_str("VectorCraft"); + } + let mut out = Vec::with_capacity(pdf.len() + 96); + out.extend_from_slice(b"\x1b%-12345X@PJL JOB NAME=\""); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(b"\"\r\n@PJL ENTER LANGUAGE=PDF\r\n"); + out.extend_from_slice(pdf); + out.extend_from_slice(b"\r\n\x1b%-12345X@PJL EOJ\r\n"); + out + } + + /// Stream `data` to the first reachable address of `host:port`. + fn send(host: &str, port: u16, data: &[u8]) -> Result<(), String> { + let addrs = (host, port).to_socket_addrs().map_err(|e| format!("direct PDF: cannot resolve {host}: {e}"))?; + let mut last = None; + for addr in addrs { + match TcpStream::connect_timeout(&addr, Duration::from_secs(10)) { + Ok(mut stream) => { + stream.set_write_timeout(Some(Duration::from_secs(120))).map_err(|e| format!("direct PDF: {e}"))?; + stream.write_all(data).map_err(|e| format!("direct PDF: writing to {host}:{port} failed: {e}"))?; + stream.shutdown(Shutdown::Write).map_err(|e| format!("direct PDF: finishing {host}:{port} failed: {e}"))?; + return Ok(()); + } + Err(e) => last = Some(e), + } + } + Err(match last { + Some(e) => format!("direct PDF: cannot connect to {host}:{port}: {e}"), + None => format!("direct PDF: {host}:{port} has no addresses"), + }) + } + + #[cfg(test)] + mod tests { + use super::*; + use std::io::Read; + use std::net::TcpListener; + + #[test] + fn the_pjl_frames_the_pdf() { + let out = pjl("witch hat\"", b"%PDF-1.7"); + let text = String::from_utf8_lossy(&out); + assert!(text.starts_with("\u{1b}%-12345X@PJL JOB NAME=\"witch hat_\"\r\n@PJL ENTER LANGUAGE=PDF\r\n")); + assert!(text.contains("%PDF-1.7")); + assert!(text.ends_with("\r\n\u{1b}%-12345X@PJL EOJ\r\n")); + } + + #[test] + fn the_pdf_reaches_a_listening_port() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let t = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut got = Vec::new(); + stream.read_to_end(&mut got).unwrap(); + got + }); + send("127.0.0.1", port, b"%PDF-1.7 test").unwrap(); + assert_eq!(t.join().unwrap(), b"%PDF-1.7 test"); + } + } +} + +#[cfg(windows)] +pub use imp::print; + +#[cfg(not(windows))] +pub fn print(_: &vectorcraft_ui_egui::print::PrintJob) -> Result { + Err("direct PDF printing is only available on Windows".into()) +} diff --git a/crates/doc/src/flare.rs b/crates/doc/src/flare.rs new file mode 100644 index 0000000000..5551bfd3ed --- /dev/null +++ b/crates/doc/src/flare.rs @@ -0,0 +1,440 @@ +//! Flare objects: the settings a flare group was drawn with (the Flare tool, `shape.flare`). Its +//! children are ordinary paths for every renderer and exporter; the settings let it be drawn again. +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Vec2, shapes}; + +use crate::Appearance; +use crate::node::{Node, NodeId, NodeKind}; + +/// The seed of the sizes a flare's rays and rings take when its settings give none. +pub const DEFAULT_SEED: u64 = 0x2545_f491_4f6c_dd1d; + +/// One part of a flare: its name, outline, fill and opacity. +pub type Part = (&'static str, PathData, Paint, f32); + +/// The number `key` of the settings `v`, or `default`. +fn number(v: &Value, key: &str, default: f64) -> f64 { + v.get(key).and_then(Value::as_f64).unwrap_or(default) +} + +/// The parts of a flare with the settings `v` (`shape.flare`'s params, each one given): a bright +/// center, a halo ring, rays of varying length and rings along the path to the end point. +pub fn parts(v: &Value) -> Vec { + let c = Point::new(number(v, "cx", 0.0), number(v, "cy", 0.0)); + let end = Point::new(number(v, "x2", c.x), number(v, "y2", c.y)); + let pct = |k: &str| (number(v, k, 0.0) / 100.0).clamp(0.0, 10.0); + let r = (number(v, "diameter", 100.0) / 2.0).max(0.5); + let opacity = pct("opacity").min(1.0) as f32; + let brightness = pct("brightness").min(1.0) as f32; + let growth = pct("growth"); + let fuzz = pct("fuzziness").min(1.0); + let rays = v.get("rays").and_then(Value::as_u64).unwrap_or(0).min(50) as usize; + let longest = pct("longest"); + let ray_fuzz = pct("rayFuzziness").min(1.0); + let ray_turn = number(v, "rotation", 0.0).to_radians(); + let rings = v.get("rings").and_then(Value::as_u64).unwrap_or(0).min(50) as usize; + let largest = pct("largest"); + // Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings + // along the path from a sequence of its own; their count and sizes and the other parts stay. + // Xorshift64. Both streams start from a nonzero state. + let random = |mut state: u64| { + move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 11) as f64 / (1u64 << 53) as f64 + } + }; + let mut rnd = random(v.get("seed").and_then(Value::as_u64).unwrap_or(DEFAULT_SEED) | 1); + // Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own. + let mut ring_at = v.get("ringSeed").and_then(Value::as_u64).filter(|r| *r < 1 << 53).map(|r| { + // SplitMix64 initializes the ring-position stream. + let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + random(z ^ (z >> 31)) + }); + let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::WHITE) }; + let radial = |centre: Point, radius: f64, stops: Vec| { + let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops)); + g.geom = Some(GradientGeom { start: centre, end: centre + Vec2::new(radius, 0.0), aspect: 1.0, focal: None }); + Paint::Gradient(Box::new(g)) + }; + let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0))); + let mut parts: Vec = vec![]; + // Halo: a soft ring just outside the centre. + let halo_r = r * (1.0 + growth) * 1.6; + let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95); + parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0)); + // Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards. + // `rotation` turns them clockwise about the center. + if rays > 0 { + let mut bp = BezPath::new(); + let mut reach: f64 = 0.0; + for i in 0..rays { + let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn; + let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1); + reach = reach.max(len); + let w = r * 0.035; + let dir = Vec2::new(a.cos(), a.sin()); + let n = Vec2::new(-dir.y, dir.x) * w; + bp.move_to(c + n); + bp.line_to(c + dir * len); + bp.line_to(c - n); + bp.line_to(c - dir * (w * 4.0)); + bp.close_path(); + } + parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0)); + } + // Centre: bright core fading to transparent. + parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity)); + // Rings along the path to the end point (Largest = % of the average ring size). + for _ in 0..rings { + let t = rnd(); + let t = ring_at.as_mut().map_or(t, |next| next()); + let at = c + (end - c) * t; + let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5); + let solid = rnd() < 0.5; + let stops = if solid { + vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)] + } else { + vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)] + }; + parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0)); + } + parts +} + +/// Part `part` of a flare as the object `id`, transformed by `xf` (the transform its flare has had +/// since it was drawn), with the pixel-aligned property when `aligned`. +pub fn part_node(id: NodeId, part: Part, xf: Affine, aligned: bool) -> Node { + let (name, pd, paint, op) = part; + let mut n = Node::path(id, pd, Appearance::basic(paint, Paint::None, 0.0)); + n.name = Some(name.into()); + n.blend = BlendMode::Screen; + n.opacity = op; + if aligned { + n.extras_mut().pixel_aligned = true; + } + if xf != Affine::IDENTITY { + n.transform(xf, false); + } + n +} + +/// The ellipse of a radial gradient's placement `geom` as the symmetric matrix `[xx, xy, yy]` that +/// maps it to the unit circle's: the same for every end point and aspect that give that ellipse +/// (transforms applied one by one and all at once can put the end on different axes of it). +fn ellipse(geom: &GradientGeom) -> [f64; 3] { + let u = geom.end - geom.start; + let w = Vec2::new(-u.y, u.x) * geom.aspect; + [u.x * u.x + w.x * w.x, u.x * u.y + w.x * w.y, u.y * u.y + w.y * w.y] +} + +/// The ellipse `[xx, xy, yy]` ([`ellipse`]) as its size, the length of its longer half-axis, and +/// its shape: the ratio of its shorter axis to its longer one, then the cosine and sine of twice +/// the longer axis's angle, each times one minus that ratio (0 for a circle). Each number is a +/// length or a ratio of lengths, never a squared length that a tiny flare or a narrow gradient +/// makes smaller than the tolerance. +fn ellipse_size_and_shape(geom: &GradientGeom) -> (f64, [f64; 3]) { + let [xx, xy, yy] = ellipse(geom); + let half_diff = (xx - yy) / 2.0; + let d = half_diff.hypot(xy); + let longer = (xx + yy) / 2.0 + d; + if longer.is_nan() || longer <= 0.0 { + return (0.0, [0.0; 3]); + } + // The product of the half-axes is the area factor of the map from the unit circle, `u` across + // `w` as [`ellipse`] builds them: a sum of squares times the aspect, without the cancellation + // of `xx * yy - xy * xy` for a narrow ellipse. + let u = geom.end - geom.start; + let w = Vec2::new(-u.y, u.x) * geom.aspect; + let ratio = ((u.x * w.y - u.y * w.x).abs() / longer).min(1.0); + let (cos, sin) = if d > 0.0 { (half_diff / d, xy / d) } else { (0.0, 0.0) }; + (longer.sqrt(), [ratio, (1.0 - ratio) * cos, (1.0 - ratio) * sin]) +} + +/// `n` as JSON without what depends on how its transforms were applied: its id, the angle of its +/// bounding box, and which axis of a gradient's ellipse its end point is on (the ellipse stays: its +/// size in the placement, and its shape beside the placement, out of reach of a pixel-aligned +/// part's snap allowance, which is a length). +fn comparable(n: &Node) -> Value { + fn strip(v: &mut Value) { + match v { + Value::Object(m) => { + for key in ["id", "bbox_angle"] { + m.remove(key); + } + if let Some(geom) = m.get_mut("geom") + && let Ok(g) = serde_json::from_value::(geom.clone()) + && let Value::Object(geom) = geom + { + let (size, shape) = ellipse_size_and_shape(&g); + geom.remove("end"); + geom.remove("aspect"); + geom.insert("ellipse".into(), serde_json::json!(size)); + m.insert("ellipseShape".into(), serde_json::json!(shape)); + } + m.values_mut().for_each(strip); + } + Value::Array(a) => a.iter_mut().for_each(strip), + _ => {} + } + } + let mut v = serde_json::to_value(n).unwrap_or(Value::Null); + strip(&mut v); + v +} + +/// How close, relative to its size, a number in an outline or a gradient's placement must be to the +/// one its transforms give: a few thousandths of a point near the edge of the canvas. +const GEOMETRY_TOL: f64 = 1e-9; + +/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size; each +/// number in an outline (`path`) or a gradient's placement (`geom`) is within [`GEOMETRY_TOL`] +/// relative to its size (or `tol`, when smaller), and `snap` points as well. +fn close(a: &Value, b: &Value, tol: f64, snap: f64, geometry: bool) -> bool { + match (a, b) { + (Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) { + (Some(x), Some(y)) => { + let (snap, tol) = if geometry { (snap, tol.min(GEOMETRY_TOL)) } else { (0.0, tol) }; + (x - y).abs() <= snap + tol * (1.0 + x.abs().max(y.abs())) + } + _ => x == y, + }, + (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| close(x, y, tol, snap, geometry)), + (Value::Object(x), Value::Object(y)) => { + x.len() == y.len() + && x.iter().all(|(k, v)| { + // A gradient's shape is ratios: compared as closely as geometry, without the snap. + let snap = if k == "ellipseShape" { 0.0 } else { snap }; + y.get(k).is_some_and(|w| close(v, w, tol, snap, geometry || k == "path" || k == "geom" || k == "ellipseShape")) + }) + } + _ => a == b, + } +} + +/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size. +pub fn json_close(a: &Value, b: &Value, tol: f64) -> bool { + close(a, b, tol, 0.0, false) +} + +/// How far a pixel-aligned object's points may be from where its transforms put them: snapping to +/// the pixel grid moves each by up to a pixel. +const PIXEL_SNAP: f64 = 1.0; + +/// The settings of a flare group ([`crate::NodeExtras::flare`]). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct FlareSpec { + /// `shape.flare`'s params the flare was drawn with, each one given: the center (`cx`, `cy`) and + /// the rings' end point (`x2`, `y2`) are in the coordinates it was drawn in. + pub params: serde_json::Value, + /// The transform its art has had since it was drawn (moves, scales, rotations, reflections and + /// shears). + #[serde(default = "identity", skip_serializing_if = "is_identity")] + pub transform: Affine, +} + +fn identity() -> Affine { + Affine::IDENTITY +} + +fn is_identity(a: &Affine) -> bool { + *a == Affine::IDENTITY +} + +impl FlareSpec { + /// The settings of a flare drawn with `params`, not transformed since. + pub fn new(params: serde_json::Value) -> Self { + Self { params, transform: Affine::IDENTITY } + } + + /// The point `key_x`, `key_y` of the params, where it is in the document now. + fn point(&self, key_x: &str, key_y: &str) -> Option { + let x = self.params.get(key_x)?.as_f64()?; + let y = self.params.get(key_y)?.as_f64()?; + Some(self.transform * Point::new(x, y)).filter(|p| p.x.is_finite() && p.y.is_finite()) + } + + /// The flare's center, where it is in the document now. + pub fn center(&self) -> Option { + self.point("cx", "cy") + } + + /// The rings' end point, where it is in the document now. + pub fn end(&self) -> Option { + self.point("x2", "y2") + } + + /// Its art transformed by `a`. + pub fn transform(&mut self, a: Affine) { + self.transform = a * self.transform; + } + + /// Whether `group`'s parts are still the ones these settings draw, in place: none was edited, + /// distorted, removed or added, and the transform can be undone. The parts are compared where + /// they are in the document, at any scale. + pub fn draws(&self, group: &Node) -> bool { + let NodeKind::Group { children, .. } = &group.kind else { return false }; + if !self.transform.is_finite() || self.transform.determinant() == 0.0 || !self.transform.inverse().is_finite() { + return false; + } + let expected = parts(&self.params); + expected.len() == children.len() + && expected.into_iter().zip(children).all(|(part, child)| { + let aligned = child.extras().pixel_aligned; + let snap = if aligned { PIXEL_SNAP } else { 0.0 }; + close(&comparable(&part_node(child.id, part, self.transform, aligned)), &comparable(child), 1e-6, snap, false) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// A flare's center and end point follow its art through a transform, and a save and reload + /// keeps its settings. + #[test] + fn a_flare_keeps_its_settings_through_a_transform_and_a_save() { + let mut g = Node::group(NodeId(1), vec![std::sync::Arc::new(Node::path(NodeId(2), PathData::default(), Default::default()))]); + g.extras_mut().flare = Some(Box::new(FlareSpec::new(json!({ "cx": 10.0, "cy": 20.0, "x2": 110.0, "y2": 20.0, "seed": 7 })))); + g.transform(Affine::translate((5.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2), false); + let spec = g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare")); + let c = spec.center().unwrap_or_else(|| panic!("no center")); + let e = spec.end().unwrap_or_else(|| panic!("no end")); + assert!((c.x - -15.0).abs() < 1e-9 && (c.y - 10.0).abs() < 1e-9, "{c:?}"); + assert!((e.x - -15.0).abs() < 1e-9 && (e.y - 110.0).abs() < 1e-9, "{e:?}"); + let text = serde_json::to_string(&g).unwrap_or_else(|e| panic!("{e}")); + let back: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(back.extras().flare.as_deref(), Some(&spec)); + // A flare that was not transformed writes no transform. + let plain = FlareSpec::new(json!({ "cx": 1.0 })); + assert_eq!(serde_json::to_value(&plain).unwrap_or_default(), json!({ "params": { "cx": 1.0 } })); + } + + /// A flare group draws its settings until a part's gradient, opacity or outline is edited; a + /// pixel-aligned part may sit up to a pixel from where its transforms put it, but only in its + /// outline and its gradient's placement. + #[test] + fn a_flare_with_an_edited_part_no_longer_draws_its_settings() { + let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0, + "opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0, + "rotation": 0.0, "largest": 50.0 }); + let flare = |aligned: bool| { + let xf = Affine::rotate(0.3) * Affine::scale_non_uniform(1.5, 0.75); + let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned))); + let mut g = Node::group(NodeId(1), children.collect()); + g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf })); + g + }; + let spec = |g: &Node| g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare")); + let edit = |g: &mut Node, f: &dyn Fn(&mut Node)| { + let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") }; + // The center, drawn at half opacity. + f(std::sync::Arc::make_mut(&mut children[2])); + }; + for aligned in [false, true] { + let g = flare(aligned); + assert!(spec(&g).draws(&g), "aligned {aligned}"); + let mut moved = g.clone(); + edit(&mut moved, &|n| n.transform(Affine::translate((0.4, 0.0)), false)); + assert_eq!(spec(&moved).draws(&moved), aligned, "a fraction of a pixel, aligned {aligned}"); + let mut faded = g.clone(); + edit(&mut faded, &|n| n.opacity *= 0.8); + assert!(!spec(&faded).draws(&faded), "opacity, aligned {aligned}"); + let mut shifted = g.clone(); + edit(&mut shifted, &|n| { + if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut() + && let Paint::Gradient(gp) = &mut fill.paint + && let Some(geom) = &mut gp.geom + { + geom.start.x += 20.0; + } + }); + assert!(!spec(&shifted).draws(&shifted), "gradient placement, aligned {aligned}"); + let mut squashed = g.clone(); + edit(&mut squashed, &|n| { + if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut() + && let Paint::Gradient(gp) = &mut fill.paint + && let Some(geom) = &mut gp.geom + { + geom.aspect *= 0.5; + } + }); + assert!(!spec(&squashed).draws(&squashed), "gradient shape, aligned {aligned}"); + } + } + + /// An ellipse's size and shape are the same whichever axis its end point is on, and a narrow + /// gradient made narrower, or turned, changes its shape by more than [`GEOMETRY_TOL`]. + #[test] + fn an_ellipse_shape_tells_narrow_gradients_apart() { + let geom = |end: (f64, f64), aspect: f64| GradientGeom { start: Point::new(1.0, 2.0), end: Point::new(end.0, end.1), aspect, focal: None }; + let of = ellipse_size_and_shape; + let (size, shape) = of(&geom((11.0, 2.0), 0.5)); + // The same ellipse with its end point on the other axis. + let (size2, shape2) = of(&geom((1.0, 7.0), 2.0)); + assert!((size - size2).abs() < 1e-12 && shape.iter().zip(shape2).all(|(a, b)| (a - b).abs() < 1e-12), "{shape:?} {shape2:?}"); + // A very narrow ellipse, given both ways, keeps its shape to within the tolerance. + let (thin, thin2) = (of(&geom((11.0, 2.0), 1e-8)).1, of(&geom((1.0, 2.0 + 1e-7), 1e8)).1); + assert!(thin.iter().zip(thin2).all(|(a, b)| (a - b).abs() < GEOMETRY_TOL), "{thin:?} {thin2:?}"); + let narrow = of(&geom((11.0, 2.0), 1e-4)).1; + for other in [of(&geom((11.0, 2.0), 5e-5)).1, of(&geom((1.0, 12.0), 1e-4)).1] { + assert!(narrow.iter().zip(other).any(|(a, b)| (a - b).abs() > 1e3 * GEOMETRY_TOL), "{narrow:?} {other:?}"); + } + assert_eq!(of(&geom((1.0, 2.0), 1.0)), (0.0, [0.0; 3])); + } + + /// A flare scaled far down, in one direction or in all, anywhere on the canvas, still draws its + /// settings, and a part's gradient whose shape was edited is still told apart; a flattened flare + /// does not draw its settings. + #[test] + fn a_flare_scaled_far_down_still_draws_its_settings() { + let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0 }); + let flare_aligned = |xf: Affine, aligned: bool| { + let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned))); + let mut g = Node::group(NodeId(1), children.collect()); + g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf })); + g + }; + let flare = |xf: Affine| flare_aligned(xf, false); + // The center's gradient placement, to edit. + let center_geom = |g: &mut Node, f: &dyn Fn(&mut GradientGeom)| { + let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") }; + if let Some(crate::AppearanceItem::Fill(fill)) = std::sync::Arc::make_mut(&mut children[2]).appearance.items.first_mut() + && let Paint::Gradient(gp) = &mut fill.paint + && let Some(geom) = &mut gp.geom + { + f(geom); + } else { + panic!("the center has no gradient fill"); + } + }; + let draws = |g: &Node| g.extras().flare.as_deref().is_some_and(|spec| spec.draws(g)); + assert!(draws(&flare(Affine::scale(1e-7))), "scaled to 0.00001%"); + assert!(draws(&flare(Affine::rotate(0.3) * Affine::scale_non_uniform(1.0, 1e-10))), "shrunk far on one axis"); + assert!(draws(&flare(Affine::translate((crate::MAX_COORD - 1000.0, 0.0)) * Affine::scale(0.5))), "near the edge of the canvas"); + assert!(draws(&flare(Affine::translate((1000.0, 0.0)) * Affine::scale(1e-5))), "scaled to 0.001% and moved away"); + assert!(!draws(&flare(Affine::scale_non_uniform(1.0, 0.0))), "flattened"); + // At that size a part whose gradient's shape was edited no longer draws the settings. + let mut squashed = flare(Affine::scale(1e-6)); + assert!(draws(&squashed), "scaled to 0.0001%"); + center_geom(&mut squashed, &|geom| geom.aspect *= 0.5); + assert!(!draws(&squashed), "gradient shape at 0.0001%"); + // A pixel-aligned part may sit up to a pixel off, but its gradient's shape may not change, + // even when the ellipse keeps its size. + let mut reshaped = flare_aligned(Affine::IDENTITY, true); + assert!(draws(&reshaped), "aligned"); + center_geom(&mut reshaped, &|geom| { + let a = geom.aspect; + geom.aspect = a * 0.5; + geom.end = geom.start + (geom.end - geom.start) * ((1.0 + a * a) / (1.0 + a * a / 4.0)).sqrt(); + }); + assert!(!draws(&reshaped), "gradient shape of the same size, aligned"); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 123e31bc08..fd1071711b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -17,6 +17,7 @@ pub mod corners; pub mod decode; pub mod depth; pub mod dimension; +pub mod flare; pub mod graph; mod halftone_radii; pub mod hit; @@ -170,7 +171,7 @@ use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; pub use stored_art::{StoredPlace, StoredRoot}; -pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number}; +pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 68aaedd68e..278ee7cf22 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -271,6 +271,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u .as_deref() .map_or(0, |m| ALLOC + size_of::() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); + b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::() + json_bytes(&f.params)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); if e.intertwine_tiers.capacity() > 0 { b += ALLOC + e.intertwine_tiers.capacity() * size_of::() + e.intertwine_tiers.iter().map(path_bytes).sum::(); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index f75e473039..06a62cb171 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -41,6 +41,9 @@ pub struct NodeExtras { /// Dimension object: the live measurement it draws; its ordinary group children hold its /// exportable appearance (Object › Dimensions, the Dimension tool). pub dimension: Option>, + /// Flare object: the settings its group was drawn with (the Flare tool); its ordinary group + /// children hold its art. + pub flare: Option>, /// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates, /// filled non-zero) where this object is drawn over the group's other members. pub intertwine: Option>, @@ -100,6 +103,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { slice: None, perspective: None, dimension: None, + flare: None, intertwine: None, intertwine_tiers: Vec::new(), live_paint_gaps: None, diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 6f72655c1d..e83aae1b09 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -520,6 +520,12 @@ impl Node { { dimension.transform(a); } + // So does a flare's center and end point. + if let Some(e) = self.extras_if_any() + && let Some(flare) = &mut e.flare + { + flare.transform(a); + } // The path the objects are attached to, before it is transformed. let on_path_before = self.on_path_data().cloned(); if !self.is_layer() { diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index c47097b8cc..2b473f0cc7 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -45,6 +45,7 @@ impl Serialize for Node { is_default(&self.bbox_angle), e.perspective.is_none(), e.dimension.is_none(), + e.flare.is_none(), e.intertwine.is_none(), e.intertwine_tiers.is_empty(), e.live_paint_gaps.is_none(), @@ -91,6 +92,7 @@ impl Serialize for Node { field!("bbox_angle", &self.bbox_angle); field!("perspective", &e.perspective); field!("dimension", &e.dimension); + field!("flare", &e.flare); field!("intertwine", &e.intertwine); field!("intertwine_tiers", &e.intertwine_tiers); field!("live_paint_gaps", &e.live_paint_gaps); @@ -228,6 +230,8 @@ pub(super) struct NodeWire { #[serde(default)] dimension: Option>, #[serde(default)] + flare: Option>, + #[serde(default)] intertwine: Option>, #[serde(default, deserialize_with = "counted_list")] intertwine_tiers: Vec, @@ -271,6 +275,7 @@ impl From for Node { slice: w.slice, perspective: w.perspective, dimension: w.dimension, + flare: w.flare, intertwine: w.intertwine, intertwine_tiers: w.intertwine_tiers, live_paint_gaps: w.live_paint_gaps, diff --git a/crates/doc/src/tests/units.rs b/crates/doc/src/tests/units.rs index c53f60a227..96fe4aab69 100644 --- a/crates/doc/src/tests/units.rs +++ b/crates/doc/src/tests/units.rs @@ -94,11 +94,59 @@ fn a_very_long_expression_reads_as_nothing() { } } +/// `x`, `X` and `×` multiply as `*` does (#8435), units and percentages included; a lowercase `x` +/// right after a `p` stays the `px` unit. +#[test] +fn x_is_a_multiplication_sign() { + let (mm, cm) = (72.0 / 25.4, 72.0 / 2.54); + for (u, s, want) in [ + (Unit::Points, "10x2", 20.0), + (Unit::Points, "10 x 2", 20.0), + (Unit::Points, "10X2", 20.0), + (Unit::Points, "10×2", 20.0), + (Unit::Points, "10x-2", -20.0), + (Unit::Points, "10/2x5", 25.0), + (Unit::Points, "1+2x3", 7.0), + (Unit::Millimeters, "2x3 mm", 6.0 * mm), + (Unit::Points, "2x3mm", 6.0 * mm), + (Unit::Points, "3mm x 2", 6.0 * mm), + (Unit::Centimeters, "3cmx50%", 1.5 * cm), + (Unit::Points, "2p x 2", 48.0), + (Unit::Points, "10px", 10.0), + (Unit::Points, "2px x 3", 6.0), + (Unit::Points, "2pxx3", 6.0), + (Unit::Millimeters, "4x3 px", 12.0), + // Only a lowercase x after a p is the px suffix. + (Unit::Points, "2pX3", 72.0), + (Unit::Points, "2p×3", 72.0), + // Text that used to be refused now reads as a product. + (Unit::Points, "8.5x11 in", 93.5 * 72.0), + (Unit::Points, "0x10", 0.0), + ] { + let got = u.parse(s).unwrap_or_else(|| panic!("{u:?} can't read `{s}`")); + assert!((got - want).abs() < 1e-9, "{u:?}: `{s}` → {got}, want {want}"); + } + for s in ["x", "x2", "5x", "5 x x 2", "xx", "2px3"] { + assert_eq!(Unit::Points.parse(s), None, "{s}"); + } + assert_eq!(crate::parse_number("45x2"), Some(90.0)); + assert_eq!(crate::parse_number(" 45 X 2 "), Some(90.0)); + assert_eq!(crate::parse_number("45×2"), Some(90.0)); + assert_eq!(crate::parse_number("90x-1"), Some(-90.0)); + assert_eq!(crate::parse_number("x"), None); + // Each sign counts toward the 128-sign limit as a `*` would. + assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(128))), Some(1.0)); + assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(129))), None); + assert_eq!(crate::parse_number(&format!("1{}", "×1".repeat(129))), None); + assert_eq!(crate::arithmetic_signs("1+2x3X4×5*6/7-8"), 7); + assert_eq!(crate::arithmetic_signs("2px x 3"), 1); +} + proptest! { /// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value /// or as nothing and does not panic. #[test] - fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxinmcfyd-]{0,24}") { + fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxXinmcfyd×-]{0,24}") { for u in Unit::ALL { if let Some(v) = u.parse(&s) { prop_assert!(v.is_finite(), "{u:?}: `{s}` → {v}"); diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 7e061d02c0..f61319326c 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -157,12 +157,17 @@ impl Unit { /// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A /// percentage on its own (`50%`) reads as nothing. /// - /// Text with more than 128 `+ - * /` signs reads as nothing. + /// `x`, `X` and `×` multiply as `*` does (`10x2` is 20, `2x3 mm` is 6 mm), except a lowercase + /// `x` right after a `p`, which is the `px` suffix (`2px x 3` is 6 px, and `2px3` reads as + /// nothing; write `2p x 3` for picas). `X` and `×` after a `p` multiply (`2pX3` is 6 picas). + /// + /// Text with more than 128 `+ - * /` signs ([`arithmetic_signs`], a multiplication sign counted + /// as `*`) reads as nothing. pub fn parse(self, s: &str) -> Option { - if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS { + if arithmetic_signs(s) > MAX_MEASURE_OPERATORS { return None; } - parse_measure(s, self).filter(|v| v.is_finite()) + parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite()) } /// The value naming this unit in the Units preferences (`points`, `millimeters`, /// `feetInches`). @@ -215,6 +220,46 @@ impl Unit { /// The most `+ - * /` signs [`Unit::parse`] reads in one text. const MAX_MEASURE_OPERATORS: usize = 128; +/// The number of `+ - * /` signs in `s`, each multiplication sign typed as `x`, `X` or `×` +/// ([`Unit::parse`]) counted as a `*`. +pub fn arithmetic_signs(s: &str) -> usize { + let mut prev = None; + s.chars() + .filter(|&c| { + let sign = matches!(c, '+' | '-' | '*' | '/') || is_times(c, prev); + prev = Some(c); + sign + }) + .count() +} + +/// Is `c`, after `prev`, a multiplication sign typed as `x`, `X` or `×`? A lowercase `x` right +/// after a `p` is the `px` suffix (`2px x 3`), also where a number follows it (`2px3`). +fn is_times(c: char, prev: Option) -> bool { + matches!(c, 'X' | '×') || (c == 'x' && prev != Some('p')) +} + +/// `s` with each multiplication sign ([`is_times`]) written as `*` (`10 x 2` is `10 * 2`); text +/// without one is not copied. +fn times_as_asterisks(s: &str) -> std::borrow::Cow<'_, str> { + let mut prev = None; + let any = s.chars().any(|c| { + let times = is_times(c, prev); + prev = Some(c); + times + }); + if !any { + return s.into(); + } + let mut out = String::with_capacity(s.len()); + let mut prev = None; + for c in s.chars() { + out.push(if is_times(c, prev) { '*' } else { c }); + prev = Some(c); + } + out.into() +} + fn parse_measure(s: &str, default: Unit) -> Option { let s = s.trim(); // Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2"). @@ -348,9 +393,10 @@ pub fn finite_in_every_unit(pt: f64) -> bool { } /// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as -/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. +/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as +/// nothing. pub fn parse_number(s: &str) -> Option { - if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/".contains(c)) { + if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) { return None; } // A leading `+` is a sign (`+5`), as a plain number read it. diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 39924835fd..6a7405648c 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -312,6 +312,36 @@ impl Carry { } } + /// Undo the actual maps of already placed gradients. Failure only changes this temporary + /// appearance; callers retain the stored row unchanged when a map cannot be inverted. + pub(crate) fn unapply_placed(&self, ap: &mut Appearance) -> Option<()> { + for step in self.0.iter().rev() { + for item in &mut ap.items { + if !matches!(item.paint(), vectorcraft_doc::color::Paint::Gradient(_)) { + continue; + } + let map = match *step { + CarryStep::Affine { m, .. } => m, + CarryStep::Boxes { from, to } => match item { + AppearanceItem::Fill(_) => crate::reshape::box_map(from, to), + AppearanceItem::Stroke(s) => crate::reshape::box_map(s.paint_bounds(from), s.paint_bounds(to)), + }, + }; + if vectorcraft_doc::node::flattens(map) { + return None; + } + let inverse = map.inverse(); + if !inverse.is_finite() { + return None; + } + if let vectorcraft_doc::color::Paint::Gradient(g) = item.paint_mut() { + g.transform(inverse); + } + } + } + Some(()) + } + pub(crate) fn push(&mut self, more: Carry) { self.0.extend(more.0); self.1.extend(more.1); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index e52a85e125..a6f5af916b 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -846,23 +846,19 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, is_guide: &impl take_held_guides(n, held, out, false, false); } -/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects -/// reshaping all its members as one piece (the whole art's bounds as their reference box) after -/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its -/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below -/// the members (after a clipping path) or above them, as its contents slot says. Its -/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live -/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and -/// a Pathfinder operation or compound shape takes the symbol instances among its members as their -/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before -/// it gives each copy those raster effects ([`copied_container`]). -pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { +struct PreparedContainer { + m: Node, + guides: Vec>, + paint: bool, + carry: crate::Carry, +} + +/// The existing container pass up to its own rows becoming art. Keep its carried appearance for +/// rendering, and retain the same Carry for freezing only missing stored placements separately. +fn prepare_container(doc: Option<&Document>, n: &Node) -> Option { if !is_container(n) { return None; } - if let Some(t) = crate::reshape::copied_container_raster_at(n) { - return Some(copied_container(doc, n, t)); - } let pathfinder = has_pathfinder(n); let fx = crate::reshape::geometry_effects(n); let paint = has_own_paint(n); @@ -870,6 +866,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { return None; } let mut m = n.clone(); + let mut carry = crate::Carry::default(); // Its ruler guides take no part: they go back above the evaluated art at the end. With effects // that replace or copy the art, so do its guides among the art and those in its sublayers and // groups, which would otherwise go with that art: they stay on `n`, in order, hidden and @@ -896,7 +893,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); members_as_drawn(doc, &mut m); } - let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); + carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. if paint && carry.moves(&m.appearance) { @@ -905,6 +902,27 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); + Some(PreparedContainer { m, guides, paint, carry }) +} + +/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects +/// reshaping all its members as one piece (the whole art's bounds as their reference box) after +/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its +/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below +/// the members (after a clipping path) or above them, as its contents slot says. Its +/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live +/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and +/// a Pathfinder operation or compound shape takes the symbol instances among its members as their +/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before +/// it gives each copy those raster effects ([`copied_container`]). +pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { + if !is_container(n) { + return None; + } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + return Some(copied_container(doc, n, t)); + } + let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?; if paint { // A clip group whose clipping type paints strokes is now a group of a clip group and those // strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside @@ -931,16 +949,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { Some(m) } -/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), -/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one -/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the -/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, -/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, -/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around -/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. -/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden -/// and locked as their containers were. -fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { +/// The exact pre-copy source shared by rendering and stored gradient placement. +fn copied_container_source(doc: Option<&Document>, n: &Node, t: usize) -> (Node, Vec>, Node) { let mut m = n.clone(); let mut guides = vec![]; take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); @@ -955,6 +965,20 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); members_as_drawn(doc, &mut source); } + (m, guides, source) +} + +/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), +/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one +/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the +/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, +/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around +/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. +/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden +/// and locked as their containers were. +fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { + let (mut m, guides, source) = copied_container_source(doc, n, t); let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| { let mut p = source.clone(); p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects); @@ -988,6 +1012,36 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { m } +/// Freeze representable fitted own paints to the box the container pass gives them, retaining +/// every live effect and already explicit placement. Hidden-only containers the pass does not +/// evaluate stay unchanged; this does not add a different fallback to `evaluate_container`. +pub fn pinned_container_appearance(doc: &Document, n: &Node) -> Option { + if !n.appearance.has_unplaced_gradient() { + return None; + } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + let (_, _, source) = copied_container_source(Some(doc), n, t); + let pinned = pinned_container_appearance(doc, &source)?; + let mut out = (*n.appearance).clone(); + out.items = pinned.items; + return Some(out); + } + let PreparedContainer { m, carry, .. } = prepare_container(Some(doc), n)?; + let bounds = m.geometric_bounds()?; + let mut out = (*n.appearance).clone(); + let mut changed = false; + for (item, original) in out.items.iter_mut().zip(&n.appearance.items) { + if paints(original) + && matches!(original.paint(), Paint::Gradient(g) if !g.is_placed()) + && let Some(pinned) = crate::pinned_gradient_item(original, bounds, &[&carry]) + { + *item = pinned; + changed = true; + } + } + changed.then_some(out) +} + /// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every /// depth of its groups and layers, by the art it draws ([`evaluate_container`], /// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 7eec83c7f5..a6b4ccece9 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -45,6 +45,7 @@ mod lighting_presets; mod live; mod marks; pub mod pixel; +mod placement; pub mod preview; mod raster; mod reshape; @@ -75,12 +76,13 @@ pub use bake::{ pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent}; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, - is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art, + is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art, }; pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; +pub use placement::pinned_gradient_item; pub use raster::{ RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects, without_geometry, diff --git a/crates/effects/src/placement.rs b/crates/effects/src/placement.rs new file mode 100644 index 0000000000..409022cef7 --- /dev/null +++ b/crates/effects/src/placement.rs @@ -0,0 +1,74 @@ +//! Conservative stored placements for gradients fitted by the existing effects passes. + +use vectorcraft_doc::color::{GradientKind, GradientPaint, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem}; +use vectorcraft_geom::Rect; + +use crate::Carry; + +/// Freeze one fitted gradient at the evaluated row's geometric bounds, before its live effects. +/// `carries` are the actual object and item passes, in rendering order. Only missing placement +/// fields are returned; explicit coordinates and the row's other data stay unchanged. A map or +/// model that cannot reproduce the original resolved row returns `None`, leaving it fitted. +pub fn pinned_gradient_item(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Option { + if gradient(item)?.is_placed() { + return Some(item.clone()); + } + if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()) { + return None; + } + let resolved = resolve(item, bounds, carries); + if !finite_placement(resolved.items.first()?) { + return None; + } + let mut stored = resolved.clone(); + for carry in carries.iter().rev() { + carry.unapply_placed(&mut stored)?; + } + if !finite_placement(stored.items.first()?) { + return None; + } + let candidate = missing_placement(item, stored.items.first()?)?; + let replayed = resolve(&candidate, bounds, carries); + (finite_placement(replayed.items.first()?) && replayed.approx_eq(&resolved)).then_some(candidate) +} + +fn gradient(item: &AppearanceItem) -> Option<&GradientPaint> { + match item.paint() { + Paint::Gradient(g) => Some(g), + _ => None, + } +} + +fn resolve(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Appearance { + let mut ap = Appearance { items: vec![item.clone()], ..Default::default() }; + for carry in carries { + carry.apply(&mut ap); + } + ap.pin_gradients(bounds); + ap +} + +fn missing_placement(item: &AppearanceItem, placed: &AppearanceItem) -> Option { + let original = gradient(item)?; + let placed = gradient(placed)?; + let mut out = item.clone(); + let Paint::Gradient(g) = out.paint_mut() else { return None }; + if original.geom.is_none() { + g.geom = placed.geom; + } + if original.gradient.kind == GradientKind::Freeform && !original.has_freeform_points() { + let freeform = placed.freeform.as_ref()?; + match &mut g.freeform { + Some(f) => f.points.clone_from(&freeform.points), + None => g.freeform = Some(freeform.clone()), + } + } + Some(out) +} + +fn finite_placement(item: &AppearanceItem) -> bool { + let Some(g) = gradient(item) else { return false }; + g.geom.is_none_or(|v| v.start.is_finite() && v.end.is_finite() && v.aspect.is_finite() && v.focal.is_none_or(|p| p.is_finite())) + && g.freeform.as_ref().is_none_or(|f| f.points.iter().all(|p| p.at.is_finite())) +} diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 00bf169b93..85c36f2d89 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -3505,7 +3505,7 @@ pub(crate) fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) { /// The map that takes box `from` onto box `to` along each axis (along an axis `from` has no extent /// on, a move from its center to `to`'s). -fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine { +pub(crate) fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine { let axis = |a0: f64, a1: f64, b0: f64, b1: f64| { if (a1 - a0).abs() > 1e-12 { let s = (b1 - b0) / (a1 - a0); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index a0fd8265dd..359fc8761f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -32,6 +32,7 @@ pub mod expand; pub(crate) mod fileinfo; pub mod fileio; pub mod findfiles; +pub mod flare; pub mod flatten; pub mod fontfiles; mod fonts; @@ -99,12 +100,13 @@ pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; mod textedit; -mod xmlattrs; pub use textedit::effective_kerning; +mod retype; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; +pub mod toast; pub(crate) mod typecmd; mod typemenu; mod variablecmds; @@ -322,6 +324,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(pathops::specs()); v.extend(compoundshape::specs()); v.extend(typecmd::specs()); + v.extend(retype::specs()); v.extend(menucmds::specs()); v.extend(live::specs()); v.extend(colorcmds::specs()); @@ -334,6 +337,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(compositefonts::specs()); v.extend(fontfiles::specs()); v.extend(help::specs()); + v.extend(toast::specs()); v.extend(threads::specs()); v.extend(textwrap::specs()); v.extend(graph::specs()); @@ -876,10 +880,14 @@ pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, /// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs). pub use compoundshape::selected_member_modes; +/// Make Compound Shape's warning when a member is an open path that encloses no area. +pub use compoundshape::OPEN_PATHS_ADD_NO_AREA; + /// Pathfinder Options (`Prefs::pathfinder`). pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions}; -/// The Attributes panel's state ([`Session::attributes_info`]). +/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps. +pub use attributes::RECENT_URLS; pub use overprint::AttributesInfo; /// Object → Flatten Transparency settings (`object.flattenTransparency`). @@ -903,6 +911,8 @@ pub(crate) use buildcmds::TracePresetChanges; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; +/// The tile counts Create Object Mosaic would use (the dialog's Use Ratio button sets them). +pub use menucmds::mosaic_counts; /// The Shape Mode commands' warning when a selected open path encloses no area. pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA; diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 2120b040e7..4d4eb9cdf8 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -1,5 +1,6 @@ //! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both -//! circles, replacing the circles or added above them. +//! circles, or three or more each joined the same way to the others within reach and united where +//! the bridges connect, replacing the circles or added above them. use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; @@ -20,6 +21,12 @@ const LABEL: &str = "Smooth Bridge"; /// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range. const RADIUS: f64 = 100.0; const RADII: (f64, f64) = (1.0, 1000.0); +/// The gap (pt) added to the smaller circle's radius to give the arcs' radius: the range. +const GAPS: (f64, f64) = (0.0, 1000.0); +/// How far apart (pt) the outlines of two of three or more circles may be for a bridge between +/// them: by default, and the range. +const REACH: f64 = 10.0; +const REACHES: (f64, f64) = (0.0, 10000.0); pub(super) fn specs() -> Vec { vec![cmd!( @@ -27,16 +34,33 @@ pub(super) fn specs() -> Vec { "Smooth Bridge", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", has_selection, bridge )] } fn bridge(s: &mut Session, p: &Value) -> Result { - let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS); + let percent = given(p, "radius", Some(RADII), C)?; + let gap = given(p, "gap", Some(GAPS), C)?; + let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH); + if percent.is_some() && gap.is_some() { + // As the parameter check words it (`EXCLUSIVE_KEYS`), for a caller that skips that check. + let (key, other) = ("radius", "gap"); + return Err(bad(C, format!("give `{key}` or `{other}`, not both"))); + } + let arc = match gap { + Some(gap) => pt::ArcRadius::Gap(gap), + None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0), + }; let keep = switch_or(p, "keepOriginals", false, C)?; - let roots = checked_ids_or_selection(s, p, C)?; + let mut roots = checked_ids_or_selection(s, p, C)?; + // An id given twice is one circle. + roots.sort_unstable(); + roots.dedup(); + if roots.len() > pt::MAX_BRIDGED_CIRCLES { + return Err(bad(C, "select at most 2000 circles to bridge")); + } let circles: Vec<(NodeId, pt::Circle)> = { let d = &s.doc()?.doc; let editable = d.editable(); @@ -48,48 +72,93 @@ fn bridge(s: &mut Session, p: &Value) -> Result { }) .collect() }; - let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else { - return Err(bad(C, "select two circles to bridge")); - }; - let (below, above) = (*below, *above); - let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0); - let outline = match at(percent) { - Ok(sp) => PathData::single(sp), - Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")), - // A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed. - Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => { - return Err(bad(C, "the circles are too far apart for this radius: raise the radius")); + if circles.len() != roots.len() || circles.len() < 2 { + return Err(bad(C, "select two or more circles to bridge")); + } + let only: Vec = circles.iter().map(|(_, c)| *c).collect(); + // Each shape: the circles it joins, in paint order, and its outline. + let (shapes, alone): (Vec<(Vec, PathData)>, Vec) = match only.as_slice() { + [a, b] => match pt::smooth_bridge(*a, *b, arc.between(*a, *b)) { + Ok(sp) => (vec![(roots_of(&circles, &[0, 1]), PathData::single(sp))], vec![]), + Err(e) => return Err(refusal(e, arc, |largest| pt::smooth_bridge(*a, *b, largest.between(*a, *b)).is_ok())), + }, + _ => { + let made = pt::bridge_many(&only, arc, reach).map_err(|e| match e { + pt::ManyError::TooManyCircles => bad(C, "select at most 2000 circles to bridge"), + pt::ManyError::TooManyBridges => bad(C, "that makes too many bridges (at most 8000): lower the reach"), + pt::ManyError::NoneInReach => bad(C, "no two circles are within reach: raise the reach"), + pt::ManyError::TooComplex => bad(C, "the bridged circles are too complex to unite"), + // Under the many-circle rules: a pair the largest radius or gap bridges on its own + // can still have a neck too thin to unite among the others. + pt::ManyError::Pair(_, _, e) => refusal(e, arc, |largest| pt::bridges_any(&only, largest, reach)), + pt::ManyError::Bad => bad(C, "select two or more circles to bridge"), + })?; + let shapes = made.joined.into_iter().map(|j| (roots_of(&circles, &j.members), j.outline)).collect(); + (shapes, roots_of(&circles, &made.alone)) } - Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")), - Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")), }; - let id = s.edit(LABEL, |d, sel| { - let id = if keep { - // A copy of the upper circle (its appearance) with the outline as its path, right above - // it; the circles stay as they are, live shapes included. - // Fresh ids throughout, its opacity mask's art included. - let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?; - let mut n = d.reid(&upper); - if let NodeKind::Path { path, live, .. } = &mut n.kind { - *path = outline; - *live = None; + let made = s.edit(LABEL, |d, sel| { + let mut made = Vec::with_capacity(shapes.len()); + if keep { + // A copy of each shape's topmost circle (its appearance) with the outline as its path, + // right above it; the circles stay as they are, live shapes included. Fresh ids + // throughout, an opacity mask's art included. + let tops: Vec = shapes.iter().filter_map(|(members, _)| members.last().copied()).collect(); + let mut beside = Beside::above(d, &tops); + for ((_, outline), top) in shapes.into_iter().zip(tops) { + let upper = d.node(top).cloned().ok_or(EngineError::NoNode(top))?; + let mut n = d.reid(&upper); + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *path = outline; + *live = None; + } + made.push(n.id); + beside.put(d, top, vec![n])?; } - let id = n.id; - let mut beside = Beside::above(d, &[above]); - beside.put(d, above, vec![n])?; beside.finish(d)?; - id } else { - // The upper circle becomes the outline (a plain path now) and the lower one goes. - if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) { - *path = outline; - *live = None; + // Each shape's topmost circle becomes its outline (a plain path now) and the others go. + let mut gone = vec![]; + for (members, outline) in shapes { + let Some((&top, rest)) = members.split_last() else { continue }; + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(top).map(|n| &mut n.kind) { + *path = outline; + *live = None; + } + made.push(top); + gone.extend_from_slice(rest); } - remove_each(d, &[below])?; - above - }; - sel.set([id]); - Ok(id) + remove_each(d, &gone)?; + } + sel.set(made.iter().chain(&alone).copied()); + Ok(made) })?; - Ok(json!({ "id": id.0 })) + let mut out = json!({ "ids": made.iter().map(|id| id.0).collect::>(), "alone": alone.iter().map(|id| id.0).collect::>() }); + if let ([id], 2) = (made.as_slice(), only.len()) { + out["id"] = json!(id.0); + } + Ok(out) +} + +/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order). +fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec { + at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect() +} + +/// The error for circles that arcs of `arc` can't bridge. A larger radius or gap bridges circles a +/// smaller one cannot, so it suggests one only when `bridges` says the largest allowed would. +fn refusal(e: pt::BridgeError, arc: pt::ArcRadius, bridges: impl FnOnce(pt::ArcRadius) -> bool) -> EngineError { + let largest = match arc { + pt::ArcRadius::Share(_) => pt::ArcRadius::Share(RADII.1 / 100.0), + pt::ArcRadius::Gap(_) => pt::ArcRadius::Gap(GAPS.1), + }; + let would = e == pt::BridgeError::TooFar && bridges(largest); + match (e, arc, would) { + (pt::BridgeError::Inside, ..) => bad(C, "one circle is inside the other"), + (pt::BridgeError::TooFar, pt::ArcRadius::Share(_), true) => bad(C, "the circles are too far apart for this radius: raise the radius"), + (pt::BridgeError::TooFar, pt::ArcRadius::Share(_), false) => bad(C, "the circles are too far apart for this radius"), + (pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), true) => bad(C, "the circles are too far apart for this gap: raise the gap"), + (pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), false) => bad(C, "the circles are too far apart for this gap"), + (pt::BridgeError::Bad, ..) => bad(C, "select two or more circles to bridge"), + } } diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 01320c07c1..745f216b68 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -1,5 +1,5 @@ -//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius, -//! and what it refuses. +//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius or +//! gap, many circles joined to their neighbors within reach, and what it refuses. use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; @@ -46,6 +46,8 @@ fn two_circles_become_one_outline_in_the_upper_ones_place() { let steps = s.doc().unwrap().history.undo.len(); let r = s.execute(BRIDGE, &json!({})).unwrap(); assert_eq!(r["id"], json!(b.0)); + assert_eq!(r["ids"], json!([b.0]), "the same result fields as for more circles"); + assert_eq!(r["alone"], json!([])); assert_eq!(top_level(&s), [b]); let d = &s.doc().unwrap().doc; let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") }; @@ -158,9 +160,11 @@ fn far_apart_nested_and_other_objects_are_refused() { assert!(e.ends_with("the circles are too far apart for this radius"), "{e}"); } assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other")); - for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] { - assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}"); + for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, square.0])] { + assert!(err(&mut s, json!({ "ids": ids })).contains("select two or more circles to bridge"), "{ids}"); } + // Three circles: each two within reach are bridged, and one inside another is refused there too. + assert!(err(&mut s, json!({"ids": [a.0, far.0, inner.0]})).contains("one circle is inside the other")); assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000")); assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`")); assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number")); @@ -169,6 +173,174 @@ fn far_apart_nested_and_other_objects_are_refused() { assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); } +/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100). +fn grid(s: &mut Session) -> Vec { + (0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect() +} + +fn ids(v: &Value) -> Vec { + v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +#[test] +fn a_grid_of_circles_joins_each_to_its_neighbors_in_one_shape() { + let mut s = session(); + let g = grid(&mut s); + select(&mut s, &g); + let steps = s.doc().unwrap().history.undo.len(); + // Reach 5: the side neighbors (4 apart) are bridged, the diagonal ones (about 13.9 apart) not. + let r = s.execute(BRIDGE, &json!({"gap": 4, "reach": 5})).unwrap(); + assert_eq!(ids(&r["ids"]), [g[8]], "one shape, in the topmost circle's place"); + assert_eq!(ids(&r["alone"]), []); + assert_eq!(top_level(&s), [g[8]]); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g[8]]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + // Its outline and a hole in each square of four circles, which no diagonal bridge fills. + let outline = path(&s, g[8]); + assert_eq!(outline.subpaths.len(), 5, "{}", outline.subpaths.len()); + let inside = |p: &vectorcraft_geom::PathData, x: f64, y: f64| p.to_bezpath().winding(vectorcraft_geom::kurbo::Point::new(x, y)) != 0; + assert!(inside(&outline, 112.0, 100.0) && inside(&outline, 100.0, 112.0) && !inside(&outline, 112.0, 112.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), g); + // Reach 15 takes in the diagonal neighbors, whose bridges fill the middle of each square. + select(&mut s, &g); + s.execute(BRIDGE, &json!({"gap": 4, "reach": 15})).unwrap(); + let outline = path(&s, g[8]); + assert_eq!(outline.subpaths.len(), 1); + assert!(inside(&outline, 112.0, 112.0)); +} + +#[test] +fn a_circle_with_no_neighbor_in_reach_stays_as_it_is() { + let mut s = session(); + let g = grid(&mut s); + let far = circle(&mut s, 300.0, 250.0, 10.0); + let pair = [circle(&mut s, 300.0, 40.0, 8.0), circle(&mut s, 320.0, 40.0, 8.0)]; + let mut all = g.clone(); + all.extend([far, pair[0], pair[1]]); + let r = s.execute(BRIDGE, &json!({"ids": all.iter().map(|i| i.0).collect::>(), "reach": 5})).unwrap(); + assert_eq!(ids(&r["ids"]), [g[8], pair[1]]); + assert_eq!(ids(&r["alone"]), [far]); + assert_eq!(top_level(&s), [g[8], far, pair[1]]); + assert!(matches!(&s.doc().unwrap().doc.node(far).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "untouched"); + let mut selected = s.doc().unwrap().selection.objects.to_vec(); + selected.sort(); + let mut want = vec![g[8], pair[1], far]; + want.sort(); + assert_eq!(selected, want, "the shapes and the circle left alone"); +} + +#[test] +fn keep_originals_adds_each_shape_above_its_topmost_circle() { + let mut s = session(); + let row: Vec = (0..3).map(|i| circle(&mut s, 100.0 + 25.0 * i as f64, 100.0, 10.0)).collect(); + let other = [circle(&mut s, 100.0, 200.0, 10.0), circle(&mut s, 122.0, 200.0, 10.0)]; + s.execute("paint.setFill", &json!({"ids": [row[2].0], "color": "#00ff00"})).unwrap(); + let all: Vec = row.iter().chain(&other).map(|i| i.0).collect(); + let r = s.execute(BRIDGE, &json!({"ids": all, "keepOriginals": true})).unwrap(); + let made = ids(&r["ids"]); + assert_eq!(made.len(), 2); + assert_eq!(top_level(&s), [row[0], row[1], row[2], made[0], other[0], other[1], made[1]]); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(made[0]).unwrap().appearance, d.node(row[2]).unwrap().appearance, "painted as the topmost circle"); + let b = d.node(made[0]).unwrap().path_data().unwrap().bounds().unwrap(); + assert!((b.x0 - 90.0).abs() < 1e-2 && (b.x1 - 160.0).abs() < 1e-2, "{b:?}"); +} + +#[test] +fn the_gap_form_gives_arcs_the_smaller_radius_plus_the_gap() { + let area_with = |p: Value| { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 124.0, 100.0, 10.0); + let mut p = p; + p["ids"] = json!([a.0, b.0]); + let id = NodeId(s.execute(BRIDGE, &p).unwrap()["id"].as_u64().unwrap()); + area(&s, id) + }; + // Radius 10 plus a gap of 4 is 140% of 10. + let (gap, percent) = (area_with(json!({"gap": 4})), area_with(json!({"radius": 140}))); + assert!((gap - percent).abs() < 1e-9, "{gap} {percent}"); + assert!(area_with(json!({"gap": 0})) < gap && gap < area_with(json!({"gap": 20}))); +} + +#[test] +fn many_circle_and_gap_refusals() { + let mut s = session(); + let a = circle(&mut s, 50.0, 100.0, 10.0); + let b = circle(&mut s, 250.0, 100.0, 10.0); + let c = circle(&mut s, 330.0, 100.0, 10.0); + let far = circle(&mut s, 380.0, 100.0, 10.0); + let before = top_level(&s); + let steps = s.doc().unwrap().history.undo.len(); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "radius": 100, "gap": 4})).contains("give `radius` or `gap`, not both")); + // Centers 200 apart: a gap of 0 does not bridge them, the largest (1000 pt) does. With centers + // 330 apart even that one closes the neck: it stays open only below 2 × √(10² + 2 × 10 × 1010) + // ≈ 285. + assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 0})).ends_with("too far apart for this gap: raise the gap")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "gap": 0})).ends_with("the circles are too far apart for this gap")); + assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 5})).contains("no two circles are within reach: raise the reach")); + // b and c are 60 apart: within a reach of 100, but too far for the default radius. + assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 100})).ends_with("too far apart for this radius: raise the radius")); + assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": -1})).contains("`reach` must be from 0 to 10000")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 1001})).contains("`gap` must be from 0 to 1000")); + assert_eq!(top_level(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); +} + +#[test] +fn a_larger_radius_is_suggested_only_when_it_bridges_among_the_other_circles() { + let mut s = session(); + // Centers 91.65 apart: the largest radius (1000%, 100 pt) bridges these two on their own, but + // with a neck about 0.0007 pt wide, too thin to unite among three or more circles. + let a = circle(&mut s, 20.0, 100.0, 10.0); + let b = circle(&mut s, 111.65, 100.0, 10.0); + let far = circle(&mut s, 380.0, 100.0, 10.0); + assert!(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": 1000})).is_ok()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).ends_with("too far apart for this radius: raise the radius")); + for radius in [100, 1000] { + let e = err(&mut s, json!({"ids": [a.0, b.0, far.0], "radius": radius, "reach": 100})); + assert!(e.ends_with("the circles are too far apart for this radius"), "{e}"); + } +} + +#[test] +fn too_many_circles_or_bridges_are_refused() { + let mut s = session(); + // 130 overlapping circles in a row: 8,385 pairs within reach. + let row: Vec = (0..130).map(|i| circle(&mut s, 20.0 + i as f64 * 0.2, 100.0, 10.0).0).collect(); + assert!(err(&mut s, json!({ "ids": row })).contains("that makes too many bridges (at most 8000): lower the reach")); + let many: Vec = (0..2001).map(|i| circle(&mut s, 20.0 + (i % 50) as f64 * 7.0, 150.0 + (i / 50) as f64 * 3.0, 1.0).0).collect(); + assert!(err(&mut s, json!({ "ids": many })).contains("select at most 2000 circles to bridge")); +} + +#[test] +fn an_id_given_twice_is_one_circle() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let r = s.execute(BRIDGE, &json!({"ids": [a.0, a.0, b.0]})).unwrap(); + assert_eq!(r["id"], json!(b.0), "two circles, bridged"); + assert_eq!(top_level(&s), [b]); +} + +#[test] +fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() { + let mut s = session(); + // Radius 3: arcs of 3 pt (100%) join a and b (2 apart) but close before reaching c (6 from b, + // within the default reach of 10). + let (a, b, c) = (circle(&mut s, 100.0, 100.0, 3.0), circle(&mut s, 108.0, 100.0, 3.0), circle(&mut s, 120.0, 100.0, 3.0)); + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + assert_eq!(ids(&r["ids"]), [b]); + assert_eq!(ids(&r["alone"]), [c]); + assert_eq!(top_level(&s), [b, c]); +} + #[test] fn locked_and_hidden_circles_are_not_bridged() { let mut s = session(); @@ -176,9 +348,9 @@ fn locked_and_hidden_circles_are_not_bridged() { let b = circle(&mut s, 150.0, 100.0, 20.0); select(&mut s, &[b]); s.execute("object.lock", &json!({})).unwrap(); - assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge")); s.execute("object.unlockAll", &json!({})).unwrap(); select(&mut s, &[a]); s.execute("object.hide", &json!({})).unwrap(); - assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge")); } diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs index b5d844709a..4da4f68b79 100644 --- a/crates/engine/src/cmd/addons/units.rs +++ b/crates/engine/src/cmd/addons/units.rs @@ -10,7 +10,7 @@ mod tests; use serde_json::{Value, json}; -use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit}; +use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit}; use vectorcraft_render::effects; use super::super::{CommandSpec, always, bad, cmd, has_selection}; @@ -22,8 +22,8 @@ const SELECTION_SIZE: &str = "addon.units.selectionSize"; const SHOWN_CHARS: usize = 64; /// The longest `value` or `unit` text `addon.units.convert` reads, in bytes. const MAX_TEXT_LEN: usize = 1024; -/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one -/// level of recursion per sign. +/// The most `+ - * /` signs `addon.units.convert` reads in one `value`, a multiplication sign +/// counted as a `*`: [`Unit::parse`] takes one level of recursion per sign. const MAX_OPERATORS: usize = 128; pub fn specs() -> Vec { @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Convert Units", [], None, - "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", always, convert ), @@ -88,9 +88,9 @@ fn convert(_: &mut Session, p: &Value) -> Result { } /// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /` -/// signs? +/// signs, a multiplication sign typed as `x`, `X` or `×` counted as a `*` ([`arithmetic_signs`])? fn readable(s: &str) -> bool { - s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS + s.len() <= MAX_TEXT_LEN && arithmetic_signs(s) <= MAX_OPERATORS } /// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON, diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index f914c53092..802fb5dfdf 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -76,6 +76,12 @@ fn values_read_as_number_fields_read_them() { assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); // A sum of 128 signs still reads. assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); + // x, X and × multiply as * does, and each counts toward the 128 signs. + assert!(near(pt(&mut s, json!({"value": "2x3 mm"})), 6.0 * 72.0 / 25.4)); + assert!(near(pt(&mut s, json!({"value": "10X2"})), 20.0)); + assert!(near(pt(&mut s, json!({"value": "0,5×4 in"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": format!("1{}", "x1".repeat(128))})), 1.0)); + assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err()); } #[test] diff --git a/crates/engine/src/cmd/attributes.rs b/crates/engine/src/cmd/attributes.rs index 684d33a53d..b257a978db 100644 --- a/crates/engine/src/cmd/attributes.rs +++ b/crates/engine/src/cmd/attributes.rs @@ -12,8 +12,9 @@ use super::overprint::{AttributesInfo, apply_overprint, edit_counted, overprint_ use super::path::paths_in; use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, str_param, targets}; -/// How many URLs the Attributes panel's recent list keeps. -const RECENT_URLS: usize = 10; +/// How many URLs the Attributes panel's recent list keeps: the most its Panel Options lets the +/// URL menu list. +pub const RECENT_URLS: usize = 30; pub fn specs() -> Vec { vec![ @@ -22,7 +23,7 @@ pub fn specs() -> Vec { "Attributes", [], None, - "{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}", + "{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info, newest first, at most 30) → {changed: objects}", has_doc, set ), diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 2f4d0388db..dc5a619adb 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -12,7 +12,8 @@ use std::sync::{Arc, LazyLock}; use serde_json::{Value, json}; use vectorcraft_brush::{ - self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation, + self as brush, ArtBrush, ArtScale, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, + Variation, }; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol}; @@ -180,6 +181,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit }, + BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows }, ]; /// Built-in library `id`, made once. @@ -233,6 +235,54 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush { Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) } } +/// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length). +fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush { + Brush { + name: name.into(), + kind: BrushKind::Art(ArtBrush { + art, + scale: ArtScale::BetweenGuides { start, end }, + colorization: Colorization::Tints, + ..Default::default() + }), + } +} + +/// Arrows: original art brushes whose stems stretch while their heads keep their proportions. +fn arrows() -> BrushLibrary { + let shaft = || black(shapes::rectangle(Rect::new(0.0, -1.0, 82.0, 1.0))); + let head = || black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (82.0, 0.0)])); + let solid = group(vec![shaft(), head()]); + let outline = group(vec![shaft(), black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (78.0, 4.0), (91.0, 0.0), (78.0, -4.0)]))]); + let double = group(vec![ + black(shapes::rectangle(Rect::new(18.0, -1.0, 82.0, 1.0))), + head(), + black(polygon(&[(24.0, -7.0), (0.0, 0.0), (24.0, 7.0), (18.0, 0.0)])), + ]); + let chevrons = group(vec![shaft(), head(), black(polygon(&[(53.0, -5.0), (66.0, 0.0), (53.0, 5.0), (56.0, 0.0)]))]); + let dashed = group( + (0..5) + .map(|i| { + let x = f64::from(i) * 16.0; + black(shapes::rectangle(Rect::new(x, -1.0, x + 10.0, 1.0))) + }) + .chain(std::iter::once(head())) + .collect(), + ); + built( + "Arrows", + Document::new(100.0, 100.0), + vec![ + arrow_art("Solid Arrow", solid, 0.0, 0.76), + arrow_art("Open Arrow", outline, 0.0, 0.76), + arrow_art("Double Arrow", double, 0.24, 0.76), + // The second chevron starts at 53 pt, so only the shaft before it stretches. + arrow_art("Chevron Arrow", chevrons, 0.0, 0.53), + arrow_art("Dashed Arrow", dashed, 0.0, 0.76), + ], + ) +} + /// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's /// own pattern, Pinstripes. fn art_ribbons() -> BrushLibrary { diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 739759afe6..b739ca5f7e 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -38,7 +38,7 @@ mod shape_builder; mod trace; pub use live_paint::live_paint_gaps; -pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation}; +pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation}; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_merge, sb_regions}; pub(crate) use trace::TracePresetChanges; diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 2eea5c2c00..02ba081477 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,8 +1,8 @@ use super::{ Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, - PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json, - is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, - switch_or, + PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, + fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, + source_nodes, source_shapes, switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. @@ -74,6 +74,44 @@ fn set_parts(g: &mut Node, mut parts: Vec>, gone: &[NodeId]) { } } +/// Whether a path named `name` directly in a Live Paint group is one of its faces or edges: the +/// name is [`FACE_NAME`] or [`EDGE_NAME`]. +fn part_name(name: Option<&str>) -> bool { + matches!(name, Some(FACE_NAME | EDGE_NAME)) +} + +/// Whether `n` is a path whose parent `parent` is a Live Paint group. +fn path_in_live_paint(d: &Document, parent: Option, n: &Node) -> bool { + n.path_data().is_some() && parent.and_then(|p| d.node(p)).is_some_and(is_live_paint) +} + +/// Clear the name of `n`, put directly in `parent`, when it is a path named like a face or an edge +/// ([`part_name`]) and `parent` is a Live Paint group, so that the group's other children +/// ([`others_in`]) keep it when its faces and edges are made again. Paste uses it. +pub(crate) fn clear_part_name(d: &Document, parent: Option, n: &mut Node) { + if part_name(n.name.as_deref()) && path_in_live_paint(d, parent, n) { + n.name = None; + } +} + +/// Refuse naming rows `ids` `name` when it is the name of a face or an edge ([`part_name`]) and one +/// of them is a path directly in a Live Paint group that is not named `name` already. Checked +/// before anything changes. +pub(crate) fn check_part_name(d: &Document, ids: &[NodeId], name: &str) -> Result<()> { + if !part_name(Some(name)) { + return Ok(()); + } + for id in ids { + if let Some(n) = d.node(*id) + && n.name.as_deref() != Some(name) + && path_in_live_paint(d, d.parent_of(*id), n) + { + return Err(EngineError::Other("`Face` and `Edge` name the faces and edges of a Live Paint group: give the path another name".into())); + } + } + Ok(()) +} + /// Select `ids` alone, without an undo step, when they are not selected that way already. fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> { let st = s.doc()?; @@ -149,11 +187,16 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result .ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?; check_live_paint_takes(d, roots)?; let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; + // The rows that join are children of the group already when Merge runs after a drag, and a joining + // path named like a face or an edge is not one of the group's parts. + let mut old_parts = old.clone(); + if let Some(ch) = old_parts.children_mut() { + ch.retain(|c| !roots.contains(&c.id)); + } // Paint to carry over: (point inside face, paint) for faces that draw; edges are matched to the // old edges below. let keep_faces: Vec<(Point, Carried)> = - b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect(); - let old_parts = old.clone(); + b::faces(&old_parts).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect(); let mut sources = source_nodes(&old); // The objects drawn in the other Live Paint groups besides their parts stay in the merged group. let mut others = vec![]; @@ -227,19 +270,22 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) } -/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost -/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint -/// group and then isolated itself. None when `isolated` is not in a Live Paint group. -pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option { - d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint)) +/// The Live Paint groups whose drawn art can be added when isolation mode leaves `isolated`, innermost +/// first: every Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated +/// Live Paint group and then isolated itself, and the group it was drawn in. Empty when `isolated` is +/// not in a Live Paint group. +pub(crate) fn isolated_live_paints(d: &Document, isolated: NodeId) -> Vec { + d.ancestry(isolated).unwrap_or_default().into_iter().rev().filter(|id| d.node(*id).is_some_and(is_live_paint)).collect() } /// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes /// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to -/// front: the paths drawn in it in isolation mode. +/// front: the paths drawn in it in isolation mode. A Live Paint group's sources group, which is +/// always hidden, does not count. fn drawn_in(g: &Node) -> Vec { fn open(n: &Node) -> bool { - n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c))) + let src = b::sources(n).filter(|_| is_live_paint(n)).map(|s| s.id); + n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().filter(|c| Some(c.id) != src).all(|c| open(c))) } others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect() } @@ -259,6 +305,189 @@ pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result) -> Spot { + let Some(p) = parent else { return Spot::Outside }; + for x in d.ancestry(p).unwrap_or_default().into_iter().rev() { + let n = d.node(x); + if n.is_some_and(is_live_paint) { + return if x == p { Spot::In(x) } else { Spot::Outside }; + } + if let Some(g) = d.parent_of(x) + && d.node(g).filter(|n| is_live_paint(n)).and_then(b::sources).is_some_and(|s| s.id == x) + { + return Spot::Source(g); + } + } + Spot::Outside +} + +/// The Live Paint groups that hold Live Paint group `g` among their paths (in their sources group, +/// at any depth), innermost first. +fn enclosing_live_paints(d: &Document, g: NodeId) -> Vec { + let mut out = vec![]; + let mut at = g; + while let Spot::Source(o) = spot_in(d, d.parent_of(at)) { + if out.contains(&o) { + break; + } + out.push(o); + at = o; + } + out +} + +/// What moving rows in the Layers panel (`layer.move`, `node.move`) does to Live Paint groups. +/// Rows that go into a Live Paint group from elsewhere are added to it as `livePaint.merge` adds +/// paths. Rows that go into or leave a group's paths (its sources group) change those paths, and +/// the group's faces and edges are made again from them, keeping the paint of the faces and edges +/// that stay, and so are those of every Live Paint group that holds a changed group among its +/// paths. Rows moved within one group's paths, or among a group's own children, change no faces. +pub(crate) struct LivePaintMove { + /// The Live Paint group the rows go into, and for each row whether it joins the group's paths. + join: Option<(NodeId, Vec)>, + /// The Live Paint group the rows go among the children of, with its sources group as it is + /// before the move. + keep_sources: Option<(NodeId, NodeId)>, + /// The Live Paint groups whose paths change. + rebuild: Vec, +} + +impl LivePaintMove { + /// Plan moving `rows` (with `copy`, copies of them) into `parent`, before anything changes. + /// Refuses rows Live Paint can't take ([`b::live_paint_takes`]) that would go among a group's + /// paths, with the message Make and Merge give. + pub(crate) fn plan(d: &Document, rows: &[NodeId], parent: Option, copy: bool) -> Result { + let to = spot_in(d, parent); + let from: Vec = rows.iter().map(|r| if copy { Spot::Outside } else { spot_in(d, d.parent_of(*r)) }).collect(); + let mut rebuild = vec![]; + for f in &from { + if let Spot::Source(g) = *f + && *f != to + && !rebuild.contains(&g) + { + rebuild.push(g); + } + } + if let Spot::Source(g) = to + && from.iter().any(|f| *f != to) + && !rebuild.contains(&g) + { + rebuild.push(g); + } + let entering: Vec = rows.iter().zip(&from).filter(|(_, f)| **f != to).map(|(r, _)| *r).collect(); + let join = match to { + Spot::In(g) if !entering.is_empty() => Some((g, from.iter().map(|f| *f != to).collect())), + _ => None, + }; + if to != Spot::Outside { + check_live_paint_takes(d, &entering)?; + } + let keep_sources = match to { + Spot::In(g) => d.node(g).and_then(b::sources).map(|s| (g, s.id)), + _ => None, + }; + Ok(Self { join, keep_sources, rebuild }) + } + + /// Whether rows join a Live Paint group, which makes the move a "Merge Live Paint" step. + pub(crate) fn joins(&self) -> bool { + self.join.is_some() + } + + /// After the rows were moved, now `moved` (in the order [`LivePaintMove::plan`] took them), + /// make the faces and edges of the groups whose paths changed again, and add the rows that + /// joined a group to it. → `moved` with the joined rows replaced by their group, once, and + /// without the faces and edges that were made again. + pub(crate) fn finish(self, d: &mut Document, sel: &mut Selection, moved: &[NodeId]) -> Result> { + // A moved object named like the sources group may now sit before it, where a lookup by name + // finds the object first. The group's own sources group goes back in front. + if let Some((g, src)) = self.keep_sources { + let ch = d.children_mut(Some(g))?; + if let Some(at) = ch.iter().position(|c| c.id == src) + && ch[..at].iter().any(|c| c.name.as_deref() == Some(SOURCES_NAME)) + { + let s = ch.remove(at); + ch.insert(0, s); + } + } + if self.join.is_none() && self.rebuild.is_empty() { + return Ok(moved.to_vec()); + } + // The group the rows join is made again by the merge below, from its paths as they are now + // and with the paint of its faces and edges as they were before the move. + let join_group = self.join.as_ref().map(|(g, _)| *g); + // A Live Paint group among another group's paths gives that group its faces and edges, so + // the groups holding a changed group among their paths are made again too, innermost first. + let mut groups: Vec = vec![]; + for g in self.rebuild.iter().copied().chain(join_group) { + for x in std::iter::once(g).chain(enclosing_live_paints(d, g)) { + if !groups.contains(&x) { + groups.push(x); + } + } + } + groups.sort_by_cached_key(|g| std::cmp::Reverse(d.ancestry(*g).map_or(0, |a| a.len()))); + let joined: Vec = match &self.join { + Some((_, mask)) => moved.iter().zip(mask).filter(|(_, j)| **j).map(|(r, _)| *r).collect(), + None => vec![], + }; + for g in groups { + if Some(g) == join_group { + let roots: Vec = std::iter::once(g).chain(joined.iter().copied()).collect(); + merge_live(d, sel, &roots)?; + } else if d.node(g).is_some() { + rebuild_paths(d, g)?; + } + } + let Some((g, mask)) = self.join else { return Ok(moved.iter().copied().filter(|r| d.node(*r).is_some()).collect()) }; + // `moved` holds each row once, so only the group can come twice. Faces and edges of the + // group moved along with the joining rows were made again, so they are left out. + let mut out = vec![]; + let mut listed = false; + for (r, j) in moved.iter().zip(&mask) { + if *j { + if !listed { + out.push(g); + listed = true; + } + } else if d.node(*r).is_some() { + out.push(*r); + } + } + Ok(out) + } +} + +/// Make Live Paint group `g`'s faces and edges again from the paths its sources group holds now, +/// with its Gap Options, carrying over the paint of the faces and edges that stay. With no path +/// left, the group keeps its sources group and its other children, and has no faces or edges. +fn rebuild_paths(d: &mut Document, g: NodeId) -> Result<()> { + let old = d.node(g).cloned().ok_or(EngineError::NoNode(g))?; + let sources = source_nodes(&old); + let mut n = old.clone(); + if source_shapes(&sources).0.is_empty() { + let src = b::sources(&old).cloned().ok_or(EngineError::NoNode(g))?; + set_parts(&mut n, vec![src], &[]); + } else { + let (children, _, _) = build_children(d, sources, old.gap_options().max_gap())?; + set_parts(&mut n, children, &[]); + repaint_from(&mut n, &old); + } + let mut changed = Beside::replacing(d, &[g]); + changed.put(d, g, vec![n])?; + changed.finish(d) +} + fn live_targets(s: &Session, p: &Value) -> Result> { let d = &s.doc()?.doc; let ids = root_ids(s, p)?; diff --git a/crates/engine/src/cmd/compoundshape.rs b/crates/engine/src/cmd/compoundshape.rs index bc93b399a5..b1c610d8bd 100644 --- a/crates/engine/src/cmd/compoundshape.rs +++ b/crates/engine/src/cmd/compoundshape.rs @@ -8,6 +8,8 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode}; +use vectorcraft_geom::{FillRule, PathData, SubPath}; +use vectorcraft_pathops as po; use vectorcraft_render::effects; use super::edit::{roots_of, selected_roots}; @@ -16,6 +18,10 @@ use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi}; const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"]; +/// Make Compound Shape's warning, which the status bar shows, when a member holds a line or another +/// open path that encloses no area once closed, and so contributes no area to the shape. +pub const OPEN_PATHS_ADD_NO_AREA: &str = "a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first"; + pub fn specs() -> Vec { vec![ cmd!( @@ -23,7 +29,7 @@ pub fn specs() -> Vec { "Make Compound Shape", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}", + "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id, warning?: when a member is or holds a line or another open path that encloses no area once closed, and so contributes no area}", has_multi, make ), @@ -157,6 +163,7 @@ fn make(s: &mut Session, p: &Value) -> Result { // all have `mode`, the topmost, or the backmost when they all subtract. let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() }; let hook = |c: &Node| effects::outline_object(Some(d), c); + let no_area = order.iter().any(|n| adds_no_area(d, n, &hook)); let style = order.into_iter().find_map(|n| top_style(d, n, &hook)); let id = s.edit("Make Compound Shape", |d, sel| { let gid = d.alloc_id(); @@ -179,7 +186,44 @@ fn make(s: &mut Session, p: &Value) -> Result { sel.set([id]); Ok(id) })?; - Ok(json!({ "id": id.0 })) + let mut out = json!({ "id": id.0 }); + if no_area { + out["warning"] = json!(OPEN_PATHS_ADD_NO_AREA); + } + Ok(out) +} + +/// Member `n` holds an open path that adds no area to a compound shape: one of the paths it takes +/// part as ([`effects::member_leaves`]), inside a group or a compound path too, has an open subpath +/// that encloses no area once closed (a straight line, or an evenodd contour traced twice), or it +/// has an open subpath and its subpaths, all closed, enclose no area together (open evenodd +/// subpaths that cancel one another or a closed subpath). The area is the one the path's fill rule +/// gives, which also keeps a self-crossing path whose signed area is zero (a bow tie) from the +/// warning, as Divide measures it. An area that can't be measured gives no warning. +fn adds_no_area(d: &Document, n: &Node, hook: effects::OutlineHook) -> bool { + effects::member_leaves(Some(d), n, Some(hook)).iter().any(|leaf| { + let (paths, rule): (Vec<&PathData>, FillRule) = match &leaf.kind { + NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule), + NodeKind::Path { path, rule, .. } => (vec![path], *rule), + _ => return false, + }; + let subpaths: Vec<&SubPath> = paths.iter().flat_map(|p| &p.subpaths).collect(); + if subpaths.iter().all(|sp| sp.closed) { + return false; + } + let closed = |sp: &SubPath| { + let mut sp = sp.clone(); + sp.closed = true; + sp + }; + // An area that can't be measured counts as an area, so a failed measurement gives no warning. + let no_area = |p: PathData| po::try_area(&p, rule).is_ok_and(|a| a <= 0.0); + subpaths.iter().filter(|sp| !sp.closed).any(|sp| { + // The signed-area test alone only holds for nonzero: evenodd can fill nothing where + // the signed area is not zero (a contour traced twice). + !(rule == FillRule::NonZero && po::encloses_area(sp)) && no_area(PathData::single(closed(sp))) + }) || (subpaths.len() > 1 && no_area(PathData::new(subpaths.iter().map(|sp| closed(sp)).collect()))) + }) } /// The paint and transparency of the frontmost shape `n` adds to a compound shape's area, from the diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 803057885a..4bf123ea17 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -55,7 +55,16 @@ pub fn specs() -> Vec { None, "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}", has_doc, - flare + super::flare::flare + ), + cmd!( + "shape.editFlare", + "Edit Flare", + [], + None, + "{ids?|id?: flares (default: the selected flares), cx?, cy? (the center, where it is drawn now), x2?, y2? (the rings' end point, where it is drawn now; else pathLength at direction from the center, both where it is drawn now, when either is given; else where it was), diameter?, opacity?, brightness?, growth?, fuzziness?, rays?, longest?, rayFuzziness?, rotation? (deg, turns the rays clockwise), pathLength?, rings?, largest?, direction? (as shape.flare: what is left out stays as it was)} draws each flare again in its place, moved, scaled, rotated, reflected or sheared as it has been since it was drawn, as one undo step (none when nothing changes); a flare whose parts were edited, or that is locked or hidden, is not one → {ids}", + has_doc, + super::flare::edit_flare ), cmd!( "shape.circleThroughPoints", @@ -515,149 +524,6 @@ fn star(s: &mut Session, p: &Value) -> Result { add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot)) } -/// Flare tool: a lens flare built from radial-gradient paths in Screen mode — a bright centre, a halo -/// ring, rays of varying length and rings along the path to the end point. -fn flare(s: &mut Session, p: &Value) -> Result { - use vectorcraft_color::{BlendMode, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; - let c = Point::new(f64_req(p, "cx", "shape.flare")?, f64_req(p, "cy", "shape.flare")?); - let numbers = [ - "diameter", - "opacity", - "brightness", - "growth", - "fuzziness", - "rays", - "longest", - "rayFuzziness", - "rotation", - "rings", - "largest", - "x2", - "y2", - "direction", - "pathLength", - "seed", - "ringSeed", - ]; - check_numbers(p, &numbers, "shape.flare")?; - let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0); - let r = (f64_or(p, "diameter", 100.0) / 2.0).max(0.5); - let opacity = pct("opacity", 50.0).min(1.0) as f32; - let brightness = pct("brightness", 30.0).min(1.0) as f32; - let growth = pct("growth", 20.0); - let fuzz = pct("fuzziness", 50.0).min(1.0); - let rays = p.get("rays").and_then(Value::as_u64).unwrap_or(15).min(50) as usize; - let longest = pct("longest", 300.0); - let ray_fuzz = pct("rayFuzziness", 100.0).min(1.0); - let ray_turn = f64_or(p, "rotation", 0.0).to_radians(); - let rings = p.get("rings").and_then(Value::as_u64).unwrap_or(10).min(50) as usize; - let largest = pct("largest", 50.0); - let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) { - (Some(x), Some(y)) => Point::new(x, y), - _ => { - let a = f64_or(p, "direction", 45.0).to_radians(); - c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0) - } - }; - // Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings - // along the path from a sequence of its own; their count and sizes and the other parts stay. - let seed_of = |key: &str| match p.get(key) { - None | Some(Value::Null) => Ok(None), - Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))), - }; - // Xorshift64. Both streams start from a nonzero state. - let random = |mut state: u64| { - move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - (state >> 11) as f64 / (1u64 << 53) as f64 - } - }; - let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1); - // Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own. - let ring_seed = match seed_of("ringSeed")? { - Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))), - r => r, - }; - let mut ring_at = ring_seed.map(|r| { - // SplitMix64 initializes the ring-position stream. - let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15); - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - random(z ^ (z >> 31)) - }); - let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) }; - let radial = |centre: Point, radius: f64, stops: Vec| { - let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops)); - g.geom = Some(GradientGeom { start: centre, end: centre + vectorcraft_geom::Vec2::new(radius, 0.0), aspect: 1.0, focal: None }); - Paint::Gradient(Box::new(g)) - }; - let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0))); - let mut parts: Vec<(&str, PathData, Paint, f32)> = vec![]; - // Halo: a soft ring just outside the centre. - let halo_r = r * (1.0 + growth) * 1.6; - let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95); - parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0)); - // Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards. - // `rotation` turns them clockwise about the center. - if rays > 0 { - let mut bp = vectorcraft_geom::BezPath::new(); - let mut reach: f64 = 0.0; - for i in 0..rays { - let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn; - let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1); - reach = reach.max(len); - let w = r * 0.035; - let dir = vectorcraft_geom::Vec2::new(a.cos(), a.sin()); - let n = vectorcraft_geom::Vec2::new(-dir.y, dir.x) * w; - bp.move_to(c + n); - bp.line_to(c + dir * len); - bp.line_to(c - n); - bp.line_to(c - dir * (w * 4.0)); - bp.close_path(); - } - parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0)); - } - // Centre: bright core fading to transparent. - parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity)); - // Rings along the path to the end point (Largest = % of the average ring size). - for _ in 0..rings { - let t = rnd(); - let t = ring_at.as_mut().map_or(t, |next| next()); - let at = c + (end - c) * t; - let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5); - let solid = rnd() < 0.5; - let stops = if solid { - vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)] - } else { - vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)] - }; - parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0)); - } - let parent = s.doc()?.target_parent()?; - let id = s.edit("Flare", |d, sel| { - let children = parts - .into_iter() - .map(|(name, pd, paint, op)| { - let mut n = Node::path(d.alloc_id(), pd, Appearance::basic(paint, Paint::None, 0.0)); - n.name = Some(name.into()); - n.blend = BlendMode::Screen; - n.opacity = op; - super::object::align_new_object(d, &mut n); - std::sync::Arc::new(n) - }) - .collect(); - let gid = d.alloc_id(); - let mut g = Node::group(gid, children); - g.name = Some("Flare".into()); - d.insert(parent, usize::MAX, g)?; - sel.set([gid]); - Ok(gid) - })?; - Ok(json!({ "id": id.0 })) -} - fn line(s: &mut Session, p: &Value) -> Result { let a = Point::new(f64_req(p, "x1", "shape.line")?, f64_req(p, "y1", "shape.line")?); let b = Point::new(f64_req(p, "x2", "shape.line")?, f64_req(p, "y2", "shape.line")?); diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index c44aa1b24a..4e753ce00c 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index bf52f580e7..694e6aeca5 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -345,18 +345,46 @@ pub(super) fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec bool { + n.appearance.items.iter().any(|item| item.is_fill() && item.visible() && !item.paint().is_none()) +} + +/// A visible painted stroke keeps open paths on the existing outline-erasure route. +pub(super) fn has_painted_stroke(n: &Node) -> bool { + n.appearance.items.iter().any( + |item| matches!(item, vectorcraft_doc::AppearanceItem::Stroke(stroke) if stroke.visible && !stroke.paint.is_none() && stroke.width > 0.0), + ) +} + +/// A container stroke that paints this target's open geometry. A clipping container's own +/// paint follows its clipping outline, and a compound shape paints its combined area instead. +/// Neither makes its descendants' implicit fill-closing edges into new stroked edges. +pub(super) fn has_painted_ancestor_stroke(doc: &Document, id: NodeId) -> bool { + doc.ancestry(id) + .unwrap_or_default() + .into_iter() + .rev() + .skip(1) + .filter_map(|id| doc.node(id)) + .take_while(|node| !node.clips() && !node.is_compound_shape()) + .any(|node| matches!(node.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && has_painted_stroke(node)) +} + /// [`target_paths`] for the tools that cut fills, with each target's geometry and fill rule: the /// members of a compound path whose members are all closed paths give the compound path itself, /// once, so its fill (holes included) is cut as one shape under its own fill rule. -pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect) -> Result> { - let closed_compound = |n: &Node| { +/// With `open_fills`, an open compound with a visible fill and no painted visible stroke does too. +pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect, open_fills: bool) -> Result> { + let area_compound = |n: &Node| { + let filled = open_fills && has_fill(n) && !has_painted_stroke(n) && !has_painted_ancestor_stroke(doc, n.id); matches!(&n.kind, NodeKind::Compound { children, .. } - if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed()))) + if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed() || filled))) }; let editable = doc.editable(); let mut out: Vec<(NodeId, PathData, FillRule)> = vec![]; for id in target_paths(doc, sel, area) { - let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| closed_compound(p) && editable(p.id)); + let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| area_compound(p) && editable(p.id)); let target = compound.map_or(id, |c| c.id); if out.iter().any(|t| t.0 == target) { continue; diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index cabe0e54e3..d97c18305c 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,10 +1,11 @@ use super::common::{ - PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, - poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt, + PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke, + has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, + set_geometry, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ - Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session, - SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, + Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point, + Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, }; use kurbo::{CubicBez, Line, PathSeg}; use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation}; @@ -266,7 +267,7 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0); let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0))? { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0), false)? { if !pd.is_closed() { continue; } @@ -340,8 +341,9 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { None => dist_to_polyline(&round, squash * q) <= r, }; let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? { - if pd.is_closed() { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? { + if erase_as_area(&st.doc, id, &pd) { + let pd = eraser_fill_operand(pd); if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { continue; } @@ -353,6 +355,34 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { apply_plan(s, "Eraser", plan) } +/// Whether the target is erased as filled area rather than as an open outline. +fn erase_as_area(doc: &Document, id: NodeId, pd: &PathData) -> bool { + // An unaggregated compound member keeps the outline route: its own appearance does not + // paint it. Eligible fill-only compounds were collected as one parent target above. + let compound_member = + doc.parent_of(id).and_then(|parent| doc.node(parent)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. })); + let filled_open = + !compound_member && !has_painted_ancestor_stroke(doc, id) && doc.node(id).is_some_and(|node| has_fill(node) && !has_painted_stroke(node)); + pd.is_closed() || filled_open +} + +/// Close only Eraser's temporary fill operand, preserving an open path's straight closing edge. +fn eraser_fill_operand(mut pd: PathData) -> PathData { + for sp in &mut pd.subpaths { + if !sp.closed { + // These endpoint handles are unused by an open path. Closing it must not activate them. + if let Some(first) = sp.anchors.first_mut() { + first.h_in = first.p; + } + if let Some(last) = sp.anchors.last_mut() { + last.h_out = last.p; + } + sp.closed = true; + } + } + pd +} + /// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a /// height above 0. fn marquee_param(v: &Value, cmd: &str) -> Result { @@ -369,7 +399,7 @@ fn marquee_param(v: &Value, cmd: &str) -> Result { } /// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or -/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges. +/// all). Closed paths and fill-only open paths lose the rectangle's area; other open paths are cut where they cross its edges. fn erase_rect(s: &mut Session, r: Rect) -> Result { let region = PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true)); @@ -392,8 +422,9 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result { }; let st = s.doc()?; let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? { - if pd.is_closed() { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r, true)? { + if erase_as_area(&st.doc, id, &pd) { + let pd = eraser_fill_operand(pd); if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { continue; } @@ -492,8 +523,9 @@ fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Vari let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0; let reach = (size + sv) / 2.0; let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? { - if pd.is_closed() { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? { + if erase_as_area(&st.doc, id, &pd) { + let pd = eraser_fill_operand(pd); if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { continue; } @@ -510,10 +542,36 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) return Ok(json!({ "ids": [] })); } let ids = s.edit(label, |d, sel| { + // Measure every original painting owner before any geometry or appearance changes. + // This includes a Compound above a Path Eraser target and containers above live art. + let owners: std::collections::BTreeSet<_> = plan.iter().flat_map(|(id, _)| d.ancestry(*id).unwrap_or_default()).collect(); + let pinned: Vec<_> = owners + .into_iter() + .filter_map(|id| { + let node = d.node(id)?; + if !node.appearance.has_unplaced_gradient() { + return None; + } + vectorcraft_render::pinned_appearance_for_geometry_edit(d, node).map(|appearance| (id, appearance)) + }) + .collect(); + for (id, appearance) in pinned { + if let Some(node) = d.node_mut(id) { + node.appearance = appearance.into(); + } + } let mut all = vec![]; let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::>()); for (id, pieces) in plan { - all.extend(replace_with_pieces(d, &mut cut, id, pieces)?); + let clipping_path = d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(|p| p.clips())); + if clipping_path { + // Keep every clipping contour in its original first child slot. An empty mask + // must also stay there so the clipped artwork cannot become the new mask. + set_geometry(d, id, PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect()))?; + all.push(id); + } else { + all.extend(replace_with_pieces(d, &mut cut, id, pieces)?); + } } cut.finish(d)?; sel.set(all.iter().copied()); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3b47fedb41..f126ac78ec 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1611,6 +1611,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } } else { super::object::keep_pixel_aligned(&mut c, sc); + super::buildcmds::clear_part_name(d, par, &mut c); new_ids.push(d.insert(par, idx, c)?); } } diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 7117899baf..d63489fb2e 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -182,7 +182,7 @@ impl Expandable { n.walk(&mut |c| { let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); e.text |= matches!(c.kind, NodeKind::Text(_)); - e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }); + e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some(); e.effects |= !c.appearance.effects.is_empty(); e.envelope |= matches!(c.kind, NodeKind::Envelope { .. }); e.blends |= matches!(c.kind, NodeKind::Blend { .. }); @@ -503,10 +503,14 @@ fn end_dimension_links(s: &mut Session, ended: &mut Vec) -> Result<() Ok(()) } +/// Makes the live shapes in `n` plain paths, and the flares plain groups of their parts. fn drop_live(n: &mut Node) { if let NodeKind::Path { live, .. } = &mut n.kind { *live = None; } + if n.extras().flare.is_some() { + n.extras_mut().flare = None; + } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { drop_live(Arc::make_mut(c)); diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index bd55624b32..8ca1fedcd7 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -297,7 +297,17 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; // Never a half-written file: see [`write_atomic`]. - write_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e)) +} + +/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the +/// file was put in place ([`vectorcraft_format::write_atomic_with`]), otherwise the path and the reason. +#[cfg(not(target_arch = "wasm32"))] +fn write_error(path: &str, error: std::io::Error) -> EngineError { + if error.get_ref().is_some_and(|e| e.is::()) { + return EngineError::Cancelled; + } + EngineError::Other(format!("{path}: {error}")) } /// [`write_file`] with what `fill` writes into the file (a save streamed into it). @@ -305,7 +315,7 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e)) } /// The save commands' writer: preserves a filesystem location refusal as a typed error. Other @@ -324,8 +334,10 @@ pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::W #[cfg(not(target_arch = "wasm32"))] pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError { - let reason = format!("{path}: {error}"); - if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) } + if !vectorcraft_format::read_only_location(&error) { + return write_error(path, error); + } + EngineError::ReadOnlyLocation(format!("{path}: {error}")) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 4e59e378a5..8249fe6b71 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -962,7 +962,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; /// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported -/// clipping path ([`image_clip`]). +/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes +/// it) is read with that path. pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -1139,13 +1140,15 @@ pub fn texture_image(bytes: &[u8]) -> Result { texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture")) } -/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed. +/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a +/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]). fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result { if width == 0 || height == 0 { return Err(err("the image is empty")); } let blob = ImageBlob::new(mime, bytes); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) + let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd)); + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip }) } /// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index e9e1e882a7..3012f7c238 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -19,6 +19,18 @@ pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, /// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one /// picture per chosen artboard (default all). pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, kind: Kind) -> Result { + encode_flattening(doc, p, use_artboards, kind, crate::flatten_raster_effects) +} + +/// [`encode`] with `flatten` turning raster effects into images. The chosen artboards are checked +/// first, so an export that is refused does not call `flatten`. +pub(super) fn encode_flattening( + doc: &Document, + p: &Value, + use_artboards: Option, + kind: Kind, + flatten: impl FnOnce(&Document) -> Option, +) -> Result { let f = super::format(kind.id()).ok_or_else(|| bad(C, "no metafile format"))?; let pick: ArtboardPick = super::encode::options(f, p)?; let n = doc.artboards.len(); @@ -26,12 +38,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, kin Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), _ => vec![pick.one(n).map_err(|e| bad(C, e))?], }; + if boards.is_empty() { + return Err(bad(C, "the document has no artboard")); + } let rects = boards .iter() .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) .collect::>>()?; + vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?; // Raster effects (shadows, glows, blurs) as images, as PDF export does. - let flat = crate::flatten_raster_effects(doc); + let flat = flatten(doc); let src = flat.as_ref().unwrap_or(doc); let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index daa20ac2b0..651ef89e19 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -69,7 +69,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "bleed", ty: "object", default: "null", - description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning", + description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so do objects that reach the trim edge on a side with a bleed but stop short of the bleed edge", }, FormatOption { name: "output", @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), @@ -295,6 +295,8 @@ pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result Result, non_printing: bool) -> usize { + let bleed = bleed.map(|b| if b.is_finite() && b > EDGE_TOLERANCE { b } else { 0.0 }); + if bleed.iter().all(|b| *b == 0.0) { + return 0; + } + let trims: Vec = match artboards { + Some(picked) => picked.iter().filter_map(|&i| doc.artboards.get(i)).map(|a| a.rect).collect(), + None => doc.artboards.iter().map(|a| a.rect).collect(), + }; + let symbols = doc.symbol_boxes(); + let mut count = 0; + // Each object with the clipping path of the layers above it. + let mut stack: Vec<(&Node, Option)> = doc.layers.iter().map(|l| (&**l, None)).collect(); + while let Some((n, clip)) = stack.pop() { + if let NodeKind::Layer { template, printable, children, clip: clipping, .. } = &n.kind { + // An opacity mask decides what shows, so a masked layer's art is not measured. + if !n.visible || *template || !(*printable || non_printing) || n.opacity <= 0.0 || n.extras().mask.is_some() { + continue; + } + // A clipping layer's first child clips the others, and its fills and strokes are an + // object of their own. + let (inner, members) = if *clipping { + let Some(own) = clip_region(children, &symbols) else { continue }; + let inner = clip.map_or(own, |c| c.intersect(own)); + if let Some(first) = children.first() + && let Drawn::Bounds(b) = clip_paint_drawn(first, inner, &symbols) + { + let b = clip.map_or(b, |c| c.intersect(b)); + if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) { + count += 1; + } + } + (Some(inner), children.get(1..).unwrap_or_default()) + } else { + (clip, &children[..]) + }; + stack.extend(members.iter().map(|c| (&**c, inner))); + continue; + } + let Drawn::Bounds(b) = drawn_bounds(n, &symbols) else { continue }; + let b = clip.map_or(b, |c| c.intersect(b)); + if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) { + count += 1; + } + } + count +} + +/// What [`drawn_bounds`] finds an object draws. +enum Drawn { + /// Nothing: it is hidden, a guide, at 0% opacity, or a path that paints nothing. + Nothing, + /// Art within these bounds. + Bounds(vectorcraft_geom::Rect), + /// Art whose bounds aren't known, which is not measured: brush art paints past the visual + /// bounds by an amount they don't give, an opacity mask hides part of what they hold, and area + /// type and type on a path are bounded by their frame or path. + Unknown, +} + +/// Whether path or compound path `n` paints: one of its fills and strokes is visible, has a paint +/// and an opacity above 0 and, a stroke, a width above 0. Other objects count as painting. +fn paints(n: &Node) -> bool { + !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + || n.appearance.items.iter().any(|i| { + i.visible() && i.opacity() > 0.0 && !i.paint().is_none() && !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) + }) +} + +/// What `n` draws on a page, by its visual bounds (strokes included): a group without a clipping +/// path by the members that draw, and a clip group by the part of them inside its clipping path +/// together with what the clipping path paints itself ([`clip_paint_drawn`]). +/// Hidden objects, guides, objects at 0% opacity and paths that paint nothing draw nothing. Art +/// with a brushed stroke that draws, in `n` or (outside groups) in the objects it holds, art with +/// an opacity mask, and area type and type on a path are [`Drawn::Unknown`]. +fn drawn_bounds(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn { + if !n.visible || n.is_guide() || n.opacity <= 0.0 || !paints(n) { + return Drawn::Nothing; + } + // An opacity mask decides what shows of the object, and the bounds of area type and type on a + // path are its frame or path, not its glyphs. + let frame_bounds = matches!(&n.kind, NodeKind::Text(t) if !matches!(t.kind, vectorcraft_doc::TextKind::Point)); + if vectorcraft_brush::reach(n) > 0.0 || n.extras().mask.is_some() || frame_bounds { + return Drawn::Unknown; + } + let members = |children: &[Arc]| { + let mut out = Some(None); + for c in children { + out = match (out, drawn_bounds(c, symbols)) { + (None, _) | (_, Drawn::Unknown) => None, + (Some(acc), Drawn::Bounds(b)) => Some(vectorcraft_geom::union_opt(acc, Some(b))), + (keep, Drawn::Nothing) => keep, + }; + } + out + }; + let measured = match &n.kind { + NodeKind::Group { clip: false, .. } => match members(n.editing_children()) { + Some(art) => art.and_then(|_| n.visual_of_members(std::iter::once(art))), + None => return Drawn::Unknown, + }, + NodeKind::Group { clip: true, children } => { + let Some(region) = clip_region(children, symbols) else { return Drawn::Nothing }; + let Some(art) = members(children.get(1..).unwrap_or_default()) else { return Drawn::Unknown }; + let art = art.map(|a| region.intersect(a)).filter(|b| b.area() > 0.0); + match children.first().map_or(Drawn::Nothing, |first| clip_paint_drawn(first, region, symbols)) { + Drawn::Unknown => return Drawn::Unknown, + Drawn::Bounds(b) => vectorcraft_geom::union_opt(art, Some(b)), + Drawn::Nothing => art, + } + } + _ if vectorcraft_brush::reach_within(n) > 0.0 => return Drawn::Unknown, + _ => n.visual_bounds_with(symbols), + }; + measured.map_or(Drawn::Nothing, Drawn::Bounds) +} + +/// The region the clipping path of a clip group or clipping layer with `children` clips to: its +/// geometric bounds, without its strokes. +fn clip_region(children: &[Arc], symbols: &vectorcraft_doc::SymbolBoxes) -> Option { + children.first()?.geometric_bounds_with(symbols) +} + +/// What clipping path `clip` paints itself ([`Node::clip_paint`]): its fills inside `region`, the +/// region it clips to, and its strokes over the clipped art, unclipped. +fn clip_paint_drawn(clip: &Node, region: vectorcraft_geom::Rect, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn { + let paint = clip.clip_paint(); + let mut out = None; + for (part, clipped) in [(paint.fill, true), (paint.stroke, false)] { + let Some(part) = part else { continue }; + match drawn_bounds(&part, symbols) { + Drawn::Unknown => return Drawn::Unknown, + Drawn::Nothing => {} + Drawn::Bounds(b) => { + let b = if clipped { region.intersect(b) } else { b }; + out = vectorcraft_geom::union_opt(out, Some(b).filter(|b| b.area() > 0.0)); + } + } + } + out.map_or(Drawn::Nothing, Drawn::Bounds) +} + +/// Whether bounds `b` reach the trim edge `t` (within [`EDGE_TOLERANCE`] on either side of it) on a +/// side where `bleed` (`[top, bottom, left, right]`) is above 0 and end before the bleed edge there. +/// Document space has y down. +fn stops_short(b: vectorcraft_geom::Rect, t: vectorcraft_geom::Rect, [top, bottom, left, right]: [f64; 4]) -> bool { + let tol = EDGE_TOLERANCE; + let across = b.x0 < t.x1 && b.x1 > t.x0; + let down = b.y0 < t.y1 && b.y1 > t.y0; + let reaches = |near: f64, far: f64, edge: f64| near <= edge + tol && far >= edge - tol; + (across && top > 0.0 && reaches(b.y0, b.y1, t.y0) && b.y0 > t.y0 - top + tol) + || (across && bottom > 0.0 && reaches(-b.y1, -b.y0, -t.y1) && b.y1 < t.y1 + bottom - tol) + || (down && left > 0.0 && reaches(b.x0, b.x1, t.x0) && b.x0 > t.x0 - left + tol) + || (down && right > 0.0 && reaches(-b.x1, -b.x0, -t.x1) && b.x1 < t.x1 + right - tol) +} + +/// The warning for `n` objects that [`short_of_bleed`] finds; `None` for none. +pub fn short_of_bleed_warning(n: usize) -> Option { + match n { + 0 => None, + 1 => Some(format!("1 object {SHORT_OF_BLEED_ONE}")), + _ => Some(format!("{n} objects {SHORT_OF_BLEED_OTHER}")), + } +} + +/// The end of [`short_of_bleed_warning`] for one object and for more. +const SHORT_OF_BLEED_ONE: &str = "reaches the trim edge but stops short of the bleed"; +const SHORT_OF_BLEED_OTHER: &str = "reach the trim edge but stop short of the bleed"; + +/// Whether `text` is a warning [`short_of_bleed_warning`] gives. +pub fn is_short_of_bleed(text: &str) -> bool { + text.ends_with(SHORT_OF_BLEED_ONE) || text.ends_with(SHORT_OF_BLEED_OTHER) +} + /// The end of the writer's warning for a page longer than 14,400 pt written with a `UserUnit` /// above 1. const SHOWN_SMALLER: &str = "so apps that ignore UserUnit show it that many times smaller"; @@ -340,7 +527,7 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option = placed.into_iter().map(Note::loss).collect(); // The editing data leaves out an Export for Screens folder outside the read roots. let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)); - let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?; + let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, true, native, || Ok(None))?; notes.extend(drawn); if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None { for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) { @@ -364,7 +551,8 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result Result>, private: impl FnOnce() -> Result)>>, ) -> Result<(Vec, Vec)> { - encode_carrying_at(cmd, doc, p, None, native, private) + encode_carrying_at(cmd, doc, p, None, false, native, private) } /// [`encode_carrying`] modified at `modified` (Unix seconds) when given, instead of the time of -/// writing. +/// writing, warning about art that stops short of the bleed when `bleed_check` is true. fn encode_carrying_at( cmd: &str, doc: &Document, p: &Value, modified: Option, + bleed_check: bool, native: impl FnOnce() -> Result>, private: impl FnOnce() -> Result)>>, ) -> Result<(Vec, Vec)> { let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?; + // Measured before the pages' background colors join the art. Only art that prints counts: + // createLayers writes non-printing layers with /PrintState /OFF, so they count only with + // includeNonPrinting, which writes them as printing art. + let set = &opts.settings; + let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 }; // The pages' background colors, behind the art (the editing data keeps them as colors). let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect()); let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?; @@ -401,6 +595,8 @@ fn encode_carrying_at( if opts.settings.leaves_out_bleed(doc) { notes.push(Note::loss(BLEED_LEFT_OUT)); } + // Art that reaches the trim edge but leaves part of the page's bleed empty. + notes.extend(short_of_bleed_warning(short).map(Note::loss)); if opts.settings.preserve_editing { if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) { opts.native = Some(native()?); diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 8a9b29fec2..7150d68dbb 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -629,6 +629,24 @@ impl std::io::Write for Counted { } } +/// A writer that fails once the work running on this thread is canceled +/// ([`crate::cancel::is_cancelled`]), so a streamed save stops writing into its temporary file. +/// It sits under the stream's buffer: it is checked once per buffer written, not per write. +struct StopsWhenCancelled(W); + +impl std::io::Write for StopsWhenCancelled { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if crate::cancel::is_cancelled() { + return Err(std::io::Error::other(crate::cancel::Cancelled)); + } + self.0.write(buf) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.0.flush() + } +} + /// The artboards a native or `.ai` save also writes to files of their own: with /// `separateArtboards`, those `range` names (default all). fn separate_boards(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result> { @@ -1026,10 +1044,15 @@ impl SaveJob { } /// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in - /// order: when `stop` returns a value, nothing is written and that value is returned. + /// order: when `stop` returns a value, nothing is written and that value is returned. Work + /// canceled ([`crate::cancel`]) before the first file is written returns + /// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the + /// others are written too. pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let (plan, doc) = (&self.plan, &*self.doc); + crate::cancel::check()?; let enc = self.encode()?; + crate::cancel::check()?; let extra = json!({ "format": plan.format.id, "warnings": enc.notes() }); let Some(path) = &plan.path else { let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?; @@ -1046,8 +1069,13 @@ impl SaveJob { if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::>()) { return Ok(stopped); } - for (p, bytes) in &files { - write(p, bytes)?; + for (i, (p, bytes)) in files.iter().enumerate() { + if i == 0 { + write(p, bytes)?; + } else { + // Once a file is in place, a Cancel no longer stops the save: the set is written whole. + crate::cancel::scope(&crate::cancel::CancelToken::new(), None, || write(p, bytes))?; + } } let bytes = files.first().map_or(0, |f| f.1.len()); let mut out = super::merge(json!({ "path": path, "bytes": bytes }), extra); @@ -1070,11 +1098,15 @@ impl SaveJob { /// [`SaveJob::write`] through `stream`, which writes the file at a path with what the filler /// it is given writes (atomically, as [`vectorcraft_format::write_atomic_with`]). A native /// file goes into it as it is encoded ([`SaveJob::streams`]), never held whole in memory; - /// other files are encoded first, then written into it. + /// other files are encoded first, then written into it. Work canceled ([`crate::cancel`]) + /// while the native file is encoded, or before its filler returns, returns + /// [`crate::EngineError::Cancelled`]: the filler fails, so `stream` keeps the file as it was + /// (the atomic writer checks once more before it puts the file in place). pub fn write_streamed(&self, stream: StreamWrite) -> Result { let (Some(path), true) = (&self.plan.path, self.streams()) else { return self.write(|p, b| stream(p, &mut |w| w.write_all(b))); }; + crate::cancel::check()?; let (cmd, f) = (self.plan.mode.command(), self.plan.format); let doc = self.doc.without_edit_modes(); let doc = match f.id { @@ -1091,16 +1123,22 @@ impl SaveJob { let mut failed = None; let mut written = 0u64; let mut fill = |w: &mut dyn std::io::Write| { - let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, w), n: 0 }; + let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, StopsWhenCancelled(w)), n: 0 }; let r = super::native::encode_to(cmd, f, &doc, &self.params, &mut out); written = out.n; - match r { + let r = match r { Ok(()) => out.inner.flush(), Err(e) => { failed = Some(e); Err(std::io::Error::other("the file couldn't be encoded")) } + }; + // The last check before the file is replaced: a canceled save leaves it as it was. + if crate::cancel::is_cancelled() { + failed = Some(crate::EngineError::Cancelled); + return Err(std::io::Error::other(crate::cancel::Cancelled)); } + r }; let r = stream(path, &mut fill); r.map_err(|e| failed.take().unwrap_or(e))?; diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 3663d3e2f6..442f38e3cc 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1349,10 +1349,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> } // The document a PDF row writes: with Include Bleed, the artboards as they are. let pdf_doc = ungrown.as_deref(); + // A PDF page of an artboard has the artboard as its trim, with or without Include Bleed. A + // page of its art's bounds has every object at its edge: it doesn't say whether art stops + // short of the bleed. + let artboard_page = o.assets.is_none() && o.layers.is_none() && o.selection.is_none(); let mut write = |doc: &Document, format: &str, options: &Value| -> Result> { // The steps are the files: an encoder's own steps (artboards, pages) are not reported. let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?; - for n in given { + for n in given.into_iter().filter(|n| artboard_page || !super::pdf::is_short_of_bleed(&n.text)) { add_note(&mut notes, n); } Ok(bytes) diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index f3161c229d..56e2a12f30 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -935,6 +935,109 @@ fn a_save_that_fails_while_streaming_leaves_the_file_as_it_was() { let _ = std::fs::remove_dir_all(&d); } +/// A save canceled (Background Save's Cancel) before it starts, while a native file streams into +/// its temporary file, or after the last byte went into it, fails with `Cancelled` and leaves the +/// file as it was, with no temporary file behind. A file encoded first is never written. +#[test] +fn a_canceled_save_leaves_the_file_as_it_was() { + /// Passes every write on, and cancels the save after the first one. + struct CancelAfterFirst<'a> { + inner: &'a mut dyn std::io::Write, + token: crate::cancel::CancelToken, + } + impl std::io::Write for CancelAfterFirst<'_> { + fn write(&mut self, b: &[u8]) -> std::io::Result { + let n = self.inner.write(b)?; + self.token.cancel(); + Ok(n) + } + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } + } + let d = tmp_dir("stream-cancel"); + // A small document's file goes in one piece; a large one's in several. + for count in [1, 1500] { + let mut s = session(2000.0, 2000.0, 1); + for i in 0..count { + s.execute("shape.rectangle", &json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10})).unwrap(); + } + let path = d.join("a.vectorcraft").to_string_lossy().to_string(); + s.execute("file.saveCopy", &json!({"path": path})).unwrap(); + let before = std::fs::read(&path).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + assert!(job.streams()); + let token = crate::cancel::CancelToken::new(); + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |p, fill| super::write_file_with(p, &mut |w| fill(&mut CancelAfterFirst { inner: w, token: token.clone() }))) + }); + assert!(matches!(r, Err(EngineError::Cancelled)), "{count}: {r:?}"); + assert_eq!(std::fs::read(&path).unwrap(), before, "{count} objects"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "no temporary file is left"); + // Canceled before it starts: the file isn't opened. + let mut opened = false; + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |_, _| { + opened = true; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)) && !opened, "{r:?}"); + } + // A file encoded first (SVG): nothing reaches the writer. + let mut s = session(200.0, 100.0, 1); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": d.join("a.svg").to_string_lossy()})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let token = crate::cancel::CancelToken::new(); + token.cancel(); + let mut writes = 0; + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |_, _| { + writes += 1; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + let r = crate::cancel::scope(&token, None, || { + job.write(|_, _| { + writes += 1; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)) && writes == 0, "{r:?}"); + assert!(!d.join("a.svg").exists()); + let _ = std::fs::remove_dir_all(&d); +} + +/// A save that writes several files (EPS with Use Artboards) and is canceled once its first file is +/// in place writes the others too and succeeds: the set is never left half written. +#[test] +fn a_save_canceled_after_its_first_file_writes_them_all() { + let d = tmp_dir("cancel-files"); + let mut s = session(100.0, 100.0, 2); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let path = d.join("logo.eps").to_string_lossy().to_string(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let token = crate::cancel::CancelToken::new(); + let mut written = vec![]; + let r = crate::cancel::scope(&token, None, || { + job.write(|p, b| { + super::write_save_file(p, b)?; + written.push(p.to_string()); + token.cancel(); + Ok(()) + }) + }); + assert!(r.is_ok(), "{r:?}"); + assert_eq!(written.len(), 3, "{written:?}"); + assert!(written.iter().all(|p| std::path::Path::new(p).is_file()), "{written:?}"); + let _ = std::fs::remove_dir_all(&d); +} + /// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them. #[test] fn a_failed_save_does_not_stamp_the_documents_dates() { diff --git a/crates/engine/src/cmd/fileio/tests_metafile.rs b/crates/engine/src/cmd/fileio/tests_metafile.rs index b02d16508b..941db4fe07 100644 --- a/crates/engine/src/cmd/fileio/tests_metafile.rs +++ b/crates/engine/src/cmd/fileio/tests_metafile.rs @@ -95,6 +95,65 @@ fn raster_effects_are_written_as_images() { assert!(kinds.contains(&114), "the shadow is an image with transparency"); } +/// An export refused for an empty or non-finite artboard among the chosen ones, or for no +/// artboard, gives the same error as before and turns no raster effect into an image; an export +/// that goes ahead does so once, and writes what `document.export` writes. +#[test] +fn a_refused_export_turns_no_raster_effects_into_images() { + use vectorcraft_geom::Rect; + use vectorcraft_metafile::Kind; + let mut s = two_boards(); + let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 30, "height": 30})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap(); + let doc = s.doc().unwrap().doc.as_ref().clone(); + let run = |doc: &vectorcraft_doc::Document, p: Value, kind: Kind| { + let mut calls = 0; + let r = super::metafile::encode_flattening(doc, &p, Some(true), kind, |d| { + calls += 1; + crate::flatten_raster_effects(d) + }); + (r.map(|e| e.files).map_err(|e| e.to_string()), calls) + }; + for kind in [Kind::Emf, Kind::Wmf] { + let (files, calls) = run(&doc, json!({}), kind); + assert_eq!(calls, 1, "{kind:?}"); + let files = files.unwrap(); + assert_eq!(files.len(), 2, "{kind:?}"); + let r = s.execute("document.export", &json!({"format": kind.id(), "useArtboards": true})).unwrap(); + let written: Vec> = r["files"].as_array().unwrap().iter().map(b64).collect(); + assert_eq!(files.into_iter().map(|(_, b)| b).collect::>(), written, "{kind:?}"); + // The first artboard is fine; the second is empty, or has a corner that isn't finite. + let x = doc.artboards[0].rect.x1 + 10.0; + for empty in [Rect::new(x, 0.0, x, 100.0), Rect::new(0.0, 0.0, f64::NAN, 100.0), Rect::new(0.0, 0.0, 100.0, f64::INFINITY)] { + let mut bad_doc = doc.clone(); + bad_doc.artboards[1].rect = empty; + for p in [json!({}), json!({"artboards": [0, 1]}), json!({"artboards": [1]})] { + let (files, calls) = run(&bad_doc, p.clone(), kind); + let e = files.err().unwrap_or_default(); + assert!(e.contains("the export region is empty"), "{kind:?} {p}: {e}"); + assert_eq!(calls, 0, "{kind:?} {p}"); + } + } + // Reversed corners are an artboard like any other. + let mut flipped = doc.clone(); + let r1 = flipped.artboards[1].rect; + flipped.artboards[1].rect = Rect::new(r1.x1, r1.y1, r1.x0, r1.y0); + let (files, calls) = run(&flipped, json!({}), kind); + assert_eq!((files.map(|f| f.len()), calls), (Ok(2), 1), "{kind:?}"); + // No artboard to write. + let mut none = doc.clone(); + none.artboards.clear(); + let (files, calls) = run(&none, json!({}), kind); + let e = files.err().unwrap_or_default(); + assert!(e.contains("the document has no artboard"), "{kind:?}: {e}"); + assert_eq!(calls, 0, "{kind:?}"); + } + // Through the command, the refusal reads as it did. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards[1].rect = Rect::new(0.0, 0.0, 0.0, 100.0); + let e = s.execute("document.export", &json!({"format": "emf", "useArtboards": true})).unwrap_err().to_string(); + assert!(e.contains("the export region is empty"), "{e}"); +} + /// Two placed images whose pixel data can't be decoded are left out of an EMF or WMF, and /// `warnings` holds the note raster exports give, once, without naming either image's key. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_pdfx.rs b/crates/engine/src/cmd/fileio/tests_pdfx.rs index 188e0158ca..424bf3a6b6 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfx.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfx.rs @@ -171,6 +171,226 @@ fn a_pdfx_file_that_leaves_out_the_document_bleed_warns() { assert!(!left_out(&warnings), "{warnings:?}"); } +/// A 200 × 100 pt document with no art, bleed `bleed` (pt). +fn bleed_session(bleed: Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("document.setup", &json!({ "bleed": bleed })).unwrap(); + s +} + +/// A rectangle from (x0, y0) to (x1, y1) without a stroke, on the current layer. +fn plain_rect(s: &mut Session, [x0, y0, x1, y1]: [f64; 4]) -> Value { + let id = s.execute("shape.rectangle", &json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + id +} + +/// The warnings of a PDF that carries the document's bleed that say art stops short of it. +fn short_of_bleed(s: &mut Session) -> Vec { + let (_, warnings) = pdf(s, json!({"bleed": {"useDocument": true}})); + warnings.into_iter().filter(|w| super::pdf::is_short_of_bleed(w)).collect() +} + +const MM: f64 = 72.0 / 25.4; + +/// A bleed raised from 2 mm to 5 mm leaves a background that filled the old bleed, and a band +/// placed against the trim edge, short of the new one: the export warns once, counting both. +#[test] +fn art_that_reaches_the_trim_edge_but_stops_short_of_the_bleed_warns() { + let mut s = bleed_session(json!(2.0 * MM)); + let (b, w, h) = (2.0 * MM, 200.0, 100.0); + plain_rect(&mut s, [-b, -b, w + b, h + b]); + plain_rect(&mut s, [0.0, 0.0, w, 20.0]); + // At 2 mm the background reaches the bleed; the band stops at the trim edge. + assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]); + s.execute("document.setup", &json!({"bleed": 5.0 * MM})).unwrap(); + assert_eq!(short_of_bleed(&mut s), ["2 objects reach the trim edge but stop short of the bleed"]); + // The PDF/X presets carry the document's bleed. + let (_, warnings) = pdf(&mut s, json!({"preset": "PDF/X-4:2010"})); + assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}"); + // A PDF/X file with a bleed on the top alone leaves out the rest of the document's bleed, and + // the background and the band stop short at the top: the warning comes right after + // BLEED_LEFT_OUT. + let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 9}})); + assert_eq!(warnings.first().map(String::as_str), Some(super::pdf::BLEED_LEFT_OUT), "{warnings:?}"); + assert_eq!(warnings.get(1).map(String::as_str), Some("2 objects reach the trim edge but stop short of the bleed"), "{warnings:?}"); + // A page without the bleed (the default preset) doesn't warn, and neither does a page of the art's bounds. + let (_, warnings) = pdf(&mut s, json!({})); + assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}"); + let (_, warnings) = pdf(&mut s, json!({"bleed": {"useDocument": true}, "useArtboards": false})); + assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}"); + // An explicit bleed counts too, and the Summary lists the warning. + let (_, warnings) = pdf(&mut s, json!({"bleed": {"top": 9, "bottom": 9, "left": 9, "right": 9}})); + assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}"); + let v = s.execute("document.pdfSettings", &json!({"bleed": {"useDocument": true}, "includeDocument": true})).unwrap(); + assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}"); + // A group counts once, measured by its visible members: a hidden member that fills the bleed + // doesn't hide a visible one at the trim edge. + let mut s = bleed_session(json!(9)); + let fill = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let side = plain_rect(&mut s, [0.0, 40.0, 20.0, 60.0]); + s.execute("object.group", &json!({"ids": [fill, band, side]})).unwrap(); + s.execute("object.hide", &json!({"ids": [fill]})).unwrap(); + assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]); + // A clip group is measured by the art inside its clipping path, not by a clipping path that + // reaches the bleed edge. + let mut s = bleed_session(json!(9)); + let art = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let clip = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + s.execute("select.set", &json!({"ids": [art, clip]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + assert_eq!(short_of_bleed(&mut s).len(), 1); + // A clipping path that paints a fill reaching the trim edge counts, though the art it clips is + // inside: in a clip group, and as an object of its own in a clipping layer. + let mut s = bleed_session(json!(9)); + let art = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]); + let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]); + s.execute("select.set", &json!({"ids": [art, clip]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap(); + assert_eq!(short_of_bleed(&mut s).len(), 1); + let mut s = bleed_session(json!(9)); + let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]); + let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]); + s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap(); + assert_eq!(short_of_bleed(&mut s).len(), 1); + // A hidden brushed member doesn't keep a group's visible art at the trim edge from counting. + let mut s = bleed_session(json!(9)); + let brushed = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap(); + let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("object.group", &json!({"ids": [brushed, band]})).unwrap(); + s.execute("object.hide", &json!({"ids": [brushed]})).unwrap(); + assert_eq!(short_of_bleed(&mut s).len(), 1); + // A clipping layer clips its art to the clipping path's geometry, not to the stroke around it: + // the stroke reaches the trim edge, but the art it clips stops 5 pt inside. + let mut s = bleed_session(json!(9)); + let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + let clip = plain_rect(&mut s, [5.0, 5.0, 195.0, 95.0]); + s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [clip], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [clip], "weight": 10})).unwrap(); + assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]); +} + +/// No warning for art that already fills the bleed, art inside the trim, a document without a +/// bleed, art on hidden, non-printing or template layers, a side without a bleed, area type, a +/// masked object, or a `.ai` save. +#[test] +fn art_that_fills_the_bleed_or_stays_inside_does_not_warn() { + let mut s = bleed_session(json!(9)); + plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + plain_rect(&mut s, [-20.0, 40.0, 50.0, 60.0]); + plain_rect(&mut s, [10.0, 10.0, 190.0, 90.0]); + assert!(short_of_bleed(&mut s).is_empty()); + // A document without a bleed has nothing to fall short of. + let mut s = bleed_session(json!(0)); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + assert!(short_of_bleed(&mut s).is_empty()); + // Layers that don't print. + for props in [json!({"visible": false}), json!({"printable": false}), json!({"template": true})] { + let mut s = bleed_session(json!(9)); + let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let mut p = props.clone(); + p["id"] = layer; + s.execute("layer.setProps", &p).unwrap(); + assert!(short_of_bleed(&mut s).is_empty(), "{props}"); + } + // A hidden object, and a group whose hidden member is the one at the trim edge. + let mut s = bleed_session(json!(9)); + let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("object.hide", &json!({"ids": [id]})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + let mut s = bleed_session(json!(9)); + let edge = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]); + s.execute("object.group", &json!({"ids": [edge, inside]})).unwrap(); + s.execute("object.hide", &json!({"ids": [edge]})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // Art that lies in the bleed alone, away from the trim edge. + let mut s = bleed_session(json!(9)); + plain_rect(&mut s, [20.0, -5.0, 60.0, -3.0]); + assert!(short_of_bleed(&mut s).is_empty()); + // A guide in a group at the trim edge. + let mut s = bleed_session(json!(9)); + let guide = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("view.guides.make", &json!({})).unwrap(); + let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]); + s.execute("object.group", &json!({"ids": [guide, inside]})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A brushed stroke, whose brush art can paint past its visual bounds, is not measured. + let mut s = bleed_session(json!(9)); + let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("brush.apply", &json!({"ids": [id], "name": "Charcoal"})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A path with no fill and no stroke paints nothing. + let mut s = bleed_session(json!(9)); + let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("paint.setFill", &json!({"ids": [id], "none": true})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // An object at 0% opacity draws nothing. + let mut s = bleed_session(json!(9)); + let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("object.setProps", &json!({"ids": [id], "opacity": 0})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A clipping layer whose clipping path lies inside the trim draws none of its art at the edge. + let mut s = bleed_session(json!(9)); + let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + plain_rect(&mut s, [10.0, 10.0, 60.0, 60.0]); + s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A bleed on the top alone: art short at the left doesn't count, art short at the top does. + let mut s = bleed_session(json!([9, 0, 0, 0])); + plain_rect(&mut s, [0.0, 30.0, 40.0, 60.0]); + assert!(short_of_bleed(&mut s).is_empty()); + plain_rect(&mut s, [60.0, 0.0, 100.0, 40.0]); + assert_eq!(short_of_bleed(&mut s).len(), 1); + // Area type is bounded by its frame, not its glyphs: a frame at the trim edge is not measured. + let mut s = bleed_session(json!(9)); + s.execute("text.create", &json!({"x": 0, "y": 0, "text": "Title", "size": 12, "area": {"width": 200, "height": 40}})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // An opacity mask decides what shows of the object, so a masked object is not measured. + let mut s = bleed_session(json!(9)); + let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let mask = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]); + s.execute("transparency.makeOpacityMask", &json!({"ids": [band, mask]})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A `.ai` save with a bleed doesn't warn: the check is PDF export's. + let mut s = bleed_session(json!(9)); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + assert_eq!(short_of_bleed(&mut s).len(), 1); + let r = s.execute("document.export", &json!({"format": "ai", "bleed": {"useDocument": true}})).unwrap(); + assert!(!r["warnings"].to_string().contains("short of the bleed"), "{}", r["warnings"]); +} + +/// The warning changes neither the art nor the page boxes. +#[test] +fn the_bleed_warning_changes_no_geometry_and_no_page_box() { + let mut s = bleed_session(json!(9)); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let before = s.doc().unwrap().doc.clone(); + let v = s.execute("document.exportPdf", &json!({"bleed": {"useDocument": true}})).unwrap(); + assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}"); + assert_eq!(s.doc().unwrap().doc, before); + let info = s.execute("document.pdfInfo", &json!({"name": "x.pdf", "dataBase64": v["dataBase64"]})).unwrap(); + let boxes = &info["pageInfo"][0]["boxes"]; + let side = |b: &Value| { + let n: Vec = b.as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect(); + (((n[2] - n[0]) * 100.0).round() / 100.0, ((n[3] - n[1]) * 100.0).round() / 100.0) + }; + assert_eq!(side(&boxes["trim"]), (200.0, 100.0), "{info}"); + assert_eq!(side(&boxes["bleed"]), (218.0, 118.0), "{info}"); +} + /// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there). fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> { fn visit(n: &vectorcraft_doc::Node, out: &mut Vec) { diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 249a3f320c..881519fbda 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -602,6 +602,56 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); } +/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, with a +/// path and with a folder, and so do relinking to the written file, placing it and opening it. +#[test] +fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip"); + // An RGB file is kept as a PNG, a CMYK one as a TIFF. + let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); + let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)]; + for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) { + let data = vectorcraft_format::base64_encode(file); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + let before = clip_group(&s.doc().unwrap().doc, group); + // Without an extension the image is written in the format it is stored in. + let path = if folder { + let out = dir.join(format!("folder-{kind}")); + std::fs::create_dir_all(&out).unwrap(); + let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap(); + r["unembedded"][0]["path"].as_str().unwrap().to_string() + } else { + let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap(); + r["path"].as_str().unwrap().to_string() + }; + let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; + assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); + for step in ["unembed", "relink"] { + if step == "relink" { + s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "linked to the file written"); + assert_eq!(clip_group(d, group), before, "{kind}, {step}, folder: {folder}"); + } + // Placing the written file gives the same clip group as placing the PSD file did. + let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap(); + let placed = NodeId(r["ids"][0].as_u64().unwrap()); + let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed); + assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, place"); + // Opening it gives a document of the image in that clip group. + s.execute("document.open", &json!({"path": path})).unwrap(); + let d = &s.doc().unwrap().doc; + let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object"); + let (anchors, even_odd, _) = clip_group(d, top); + assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, open"); + } +} + /// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a /// text chunk within the size limit that reads as a path gives one back. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index c7c258b304..74356b6f31 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -610,6 +610,35 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() { assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row})))); } +/// A PDF row with a bleed warns about art that reaches an artboard's edge and stops short of the +/// bleed, with or without Include Bleed: the page's trim is the artboard either way. It doesn't +/// warn about art that reaches the bleed, or on a page of a selection's bounds. +#[test] +fn pdf_rows_warn_about_art_short_of_the_bleed_on_artboard_pages_only() { + let warned = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())); + let row = json!([{"format": "pdf", "bleed": {"useDocument": true}}]); + let mut s = session(1); + s.execute("document.setup", &json!({"bleed": 6})).unwrap(); + // Against the artboard's top edge. + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap(); + assert!(warned(&export(&mut s, json!({"formats": row})))); + assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row})))); + assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": [{"format": "pdf"}]}))), "the row takes the document's bleed"); + assert!(!warned(&export(&mut s, json!({"selection": "one", "formats": row})))); + assert!(!warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row})))); + // Out to the bleed edge on the top, left and right. + let mut s = session(1); + s.execute("document.setup", &json!({"bleed": 6})).unwrap(); + s.execute("shape.rectangle", &json!({"x": -6, "y": -6, "width": 52, "height": 16})).unwrap(); + assert!(!warned(&export(&mut s, json!({"formats": row})))); + assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row})))); + // Without a document bleed, a row's own bleed warns. + let mut s = session(1); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap(); + let row = json!([{"format": "pdf", "bleed": {"top": 6, "bottom": 6, "left": 6, "right": 6}}]); + assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row})))); +} + /// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read /// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries). fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> { diff --git a/crates/engine/src/cmd/flare.rs b/crates/engine/src/cmd/flare.rs new file mode 100644 index 0000000000..8871ddf921 --- /dev/null +++ b/crates/engine/src/cmd/flare.rs @@ -0,0 +1,246 @@ +//! Flares (the Flare tool): `shape.flare` draws a group of radial-gradient paths that keeps the +//! settings it was drawn with ([`FlareSpec`]), and `shape.editFlare` draws it again from them. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::flare::{DEFAULT_SEED, FlareSpec, json_close, part_node, parts}; +use vectorcraft_doc::{Document, Node, NodeId}; +use vectorcraft_geom::{Affine, Point, Vec2}; + +use super::{EngineError, Result, Session, bad, check_numbers, f64_or, f64_req, given_objects, number_or}; + +const C: &str = "shape.editFlare"; + +/// `shape.flare`'s settings besides the center, the rings' end point, the counts and the seed: +/// (key, default). +const SETTINGS: [(&str, f64); 9] = [ + ("diameter", 100.0), + ("opacity", 50.0), + ("brightness", 30.0), + ("growth", 20.0), + ("fuzziness", 50.0), + ("longest", 300.0), + ("rayFuzziness", 100.0), + ("rotation", 0.0), + ("largest", 50.0), +]; + +/// The whole number of 0 or more `p` gives for `key`, or `default`. +fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result { + let n = number_or(p, key, default as f64, cmd)?; + if n.is_finite() && n >= 0.0 && n.fract() == 0.0 { + Ok(n as u64) + } else { + Err(bad(cmd, format!("`{key}` must be a whole number of at least 0, not {n}"))) + } +} + +/// `end`, the rings' end point, or an error naming `x2` or `y2` when that coordinate is not a +/// finite number (a `pathLength` so large that the end point overflows). +fn finite_end(end: Point, cmd: &str) -> Result { + match [("x2", end.x), ("y2", end.y)].into_iter().find(|(_, v)| !v.is_finite()) { + None => Ok(end), + Some((key, _)) => Err(bad(cmd, format!("{key} must be a finite coordinate"))), + } +} + +/// `shape.flare`'s params `p` with every setting given: the defaults filled in, the counts at most +/// 50 and the rings' end point as `x2`, `y2` (from `pathLength` and `direction` when `p` gives no +/// end point), with `ringSeed` when `p` gives one. +fn settings_of(p: &Value, cmd: &str) -> Result { + let c = Point::new(f64_req(p, "cx", cmd)?, f64_req(p, "cy", cmd)?); + let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect(); + numbers.extend(["x2", "y2", "direction", "pathLength", "seed", "ringSeed"]); + check_numbers(p, &numbers, cmd)?; + let seed_of = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 0, not {v}"))), + }; + let seed = seed_of("seed")?.unwrap_or(DEFAULT_SEED); + // Each `ringSeed` below 2^53 (what a JSON number holds exactly) places the rings anew. + let ring_seed = match seed_of("ringSeed")? { + Some(r) if r >= 1 << 53 => return Err(bad(cmd, format!("`ringSeed` must be below 2^53, not {r}"))), + r => r, + }; + let rays = count_or(p, "rays", 15, cmd)?.min(50); + let rings = count_or(p, "rings", 10, cmd)?.min(50); + let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) { + (Some(x), Some(y)) => Point::new(x, y), + _ => { + let a = f64_or(p, "direction", 45.0).to_radians(); + finite_end(c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0), cmd)? + } + }; + let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed }); + if let Some(r) = ring_seed { + v["ringSeed"] = json!(r); + } + for (key, default) in SETTINGS { + v[key] = json!(f64_or(p, key, default)); + } + Ok(v) +} + +/// The objects of a flare drawn with the settings `v`, transformed by `xf`. A new flare's parts +/// (`old` None) get new ids and take the document's Align New Objects to Pixel Grid. A flare drawn +/// again from its parts `old` keeps, for each part, the id and pixel-aligned property of the old +/// part it replaces (the same kind of part, counted in order: the second ring replaces the second +/// ring); a part that replaces none gets a new id and the first old part's property. +fn part_nodes(d: &mut Document, v: &Value, xf: Affine, old: Option<&[Arc]>) -> Vec> { + let mut seen: Vec<&str> = vec![]; + parts(v) + .into_iter() + .map(|part| { + let name = part.0; + let nth = seen.iter().filter(|n| **n == name).count(); + seen.push(name); + let replaced = old.and_then(|old| old.iter().filter(|c| c.name.as_deref() == Some(name)).nth(nth)); + let id = replaced.map_or_else(|| d.alloc_id(), |c| c.id); + let mut n = part_node(id, part, Affine::IDENTITY, false); + match old { + None => super::object::align_new_object(d, &mut n), + Some(old) => n.extras_mut().pixel_aligned = replaced.or(old.first()).is_some_and(|c| c.extras().pixel_aligned), + } + if xf != Affine::IDENTITY { + n.transform(xf, false); + } + Arc::new(n) + }) + .collect() +} + +/// `shape.flare`: a flare group that keeps its settings. +pub(super) fn flare(s: &mut Session, p: &Value) -> Result { + let v = settings_of(p, "shape.flare")?; + let parent = s.doc()?.target_parent()?; + let id = s.edit("Flare", |d, sel| { + let children = part_nodes(d, &v, Affine::IDENTITY, None); + let gid = d.alloc_id(); + let mut g = Node::group(gid, children); + g.name = Some("Flare".into()); + g.extras_mut().flare = Some(Box::new(FlareSpec::new(v))); + d.insert(parent, usize::MAX, g)?; + sel.set([gid]); + Ok(gid) + })?; + Ok(json!({ "id": id.0 })) +} + +/// The settings of flare `id`: a group drawn by the Flare tool whose parts are still the ones its +/// settings draw, in place ([`FlareSpec::draws`]). A flare whose parts were edited, distorted, +/// removed or added to, or whose art was flattened to a line, is no longer one. +pub fn flare_settings(d: &Document, id: NodeId) -> Option { + let n = d.node(id)?; + let spec = n.extras().flare.as_deref()?; + // Settings a file holds are read as `shape.flare` reads them. + let spec = FlareSpec { params: settings_of(&spec.params, "shape.flare").ok()?, transform: spec.transform }; + spec.draws(n).then_some(spec) +} + +/// The flares `shape.editFlare` changes: those `p` names, else the selected flares. Each must be a +/// flare that can be edited. +fn flares_to_edit(s: &Session, p: &Value) -> Result> { + let given = given_objects(s, p, C)?; + let d = &s.doc()?.doc; + let flare = |id: NodeId| flare_settings(d, id).filter(|_| d.is_editable(id)).map(|spec| (id, spec)); + let flares: Vec<(NodeId, FlareSpec)> = match &given { + Some(ids) => ids.iter().map(|id| flare(*id)).collect::>>().unwrap_or_default(), + None => s.doc()?.selection.objects.iter().filter_map(|id| flare(*id)).collect(), + }; + if flares.is_empty() { + return Err(EngineError::Other("select a flare".into())); + } + Ok(flares) +} + +/// The settings `old` changed as `p` asks (`shape.editFlare`'s params). The center and the end +/// point `p` gives are in the document, where the flare is now drawn, which `xf` maps from where +/// it was drawn. +fn edited(old: &Value, p: &Value, xf: Affine) -> Result { + let mut v = old.clone(); + let inv = xf.inverse(); + let point = |kx: &str, ky: &str| -> Result> { + if p.get(kx).is_none_or(Value::is_null) && p.get(ky).is_none_or(Value::is_null) { + return Ok(None); + } + // A point that leaves the finite range where the flare was drawn is refused, not stored. + let q = inv * Point::new(f64_req(p, kx, C)?, f64_req(p, ky, C)?); + match [(kx, q.x), (ky, q.y)].into_iter().find(|(_, v)| !v.is_finite()) { + None => Ok(Some(q)), + Some((key, _)) => Err(bad(C, format!("{key} must be a finite coordinate"))), + } + }; + let c = point("cx", "cy")?; + let end = point("x2", "y2")?; + if let Some(c) = c { + v["cx"] = json!(c.x); + v["cy"] = json!(c.y); + } + let centre = Point::new(f64_or(&v, "cx", 0.0), f64_or(&v, "cy", 0.0)); + let old_end = Point::new(f64_or(&v, "x2", centre.x), f64_or(&v, "y2", centre.y)); + let end = match end { + Some(e) => e, + None if p.get("pathLength").is_some_and(|l| !l.is_null()) || p.get("direction").is_some_and(|a| !a.is_null()) => { + // The path length and the direction are where the flare is drawn now; the direction is + // measured counter-clockwise from 3 o'clock, as `shape.flare` takes it. + let (c, e) = (xf * centre, xf * old_end); + let d = e - c; + let a = number_or(p, "direction", (-d.y).atan2(d.x).to_degrees(), C)?.to_radians(); + finite_end(inv * (c + Vec2::new(a.cos(), -a.sin()) * number_or(p, "pathLength", d.hypot(), C)?), C)? + } + // Moving the center leaves the rings' end point where it is. + None => old_end, + }; + v["x2"] = json!(end.x); + v["y2"] = json!(end.y); + for (key, _) in SETTINGS { + if p.get(key).is_some_and(|x| !x.is_null()) { + v[key] = json!(number_or(p, key, 0.0, C)?); + } + } + for key in ["rays", "rings"] { + if p.get(key).is_some_and(|x| !x.is_null()) { + v[key] = json!(count_or(p, key, 0, C)?.min(50)); + } + } + settings_of(&v, C) +} + +/// `shape.editFlare`: draw the flares again with the settings `p` changes, each in its place and +/// transformed as it has been since it was drawn, as one undo step. +pub(super) fn edit_flare(s: &mut Session, p: &Value) -> Result { + let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect(); + numbers.extend(["cx", "cy", "x2", "y2", "pathLength", "direction", "rays", "rings"]); + check_numbers(p, &numbers, C)?; + let flares = flares_to_edit(s, p)?; + let mut changed: Vec<(NodeId, FlareSpec)> = vec![]; + for (id, spec) in &flares { + let v = edited(&spec.params, p, spec.transform)?; + if !json_close(&v, &spec.params, 1e-9) { + changed.push((*id, FlareSpec { params: v, transform: spec.transform })); + } + } + let ids: Vec = flares.iter().map(|(id, _)| id.0).collect(); + // Nothing changes: no undo step. + if changed.is_empty() { + return Ok(json!({ "ids": ids })); + } + let edited_ids: Vec = changed.iter().map(|(id, _)| *id).collect(); + s.edit("Edit Flare", |d, _| { + for (id, spec) in changed { + let old: Vec> = d.node(id).and_then(Node::children).cloned().unwrap_or_default(); + let children = part_nodes(d, &spec.params, spec.transform, Some(&old)); + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().flare = Some(Box::new(spec)); + } + if !crate::sanity::objects_in_range(d, &edited_ids) { + return Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into())); + } + Ok(()) + })?; + Ok(json!({ "ids": ids })) +} diff --git a/crates/engine/src/cmd/fontfiles.rs b/crates/engine/src/cmd/fontfiles.rs index fde85dd92d..c13b256210 100644 --- a/crates/engine/src/cmd/fontfiles.rs +++ b/crates/engine/src/cmd/fontfiles.rs @@ -19,23 +19,6 @@ use crate::DocState; const MAX_FONTS: usize = 1_000; /// The longest family or style name listed or given (bytes). const MAX_NAME: usize = 256; -/// The CSS generic font families (CSS Fonts Module Level 4), which SVG and HTML files name in place -/// of a font and no font file provides; compared in any ASCII case. The list leaves out -/// `fangsong`, which is also the family name of a Chinese font (FangSong). -const GENERIC_FAMILIES: &[&str] = &[ - "serif", - "sans-serif", - "monospace", - "cursive", - "fantasy", - "system-ui", - "ui-serif", - "ui-sans-serif", - "ui-monospace", - "ui-rounded", - "math", - "emoji", -]; /// The longest folder path given (bytes). const MAX_PATH: usize = 4096; /// The most files one `text.addFontFiles` copies: as many as a search keeps. @@ -105,10 +88,10 @@ pub struct MissingFont { /// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those /// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif` -/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out. +/// ([`vectorcraft_text::GENERIC_FAMILIES`]) and names longer than 256 bytes are left out. pub fn missing_fonts(d: &Document) -> Vec { let db = FontDb::global(); - let generic = |family: &str| GENERIC_FAMILIES.iter().any(|g| g.eq_ignore_ascii_case(family.trim())); + let generic = vectorcraft_text::is_generic_family; let mut used: Vec<(String, String)> = super::fonts::used_fonts(d).into_iter().map(|(family, style, _)| (family, style)).collect(); // Sorted by family and style: the versions type names of one face are neighbors. used.dedup(); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 7a7f2b8e08..f7632f2652 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -13,6 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, Scaling}; use vectorcraft_geom::{Affine, Rect}; +use super::buildcmds::LivePaintMove; use super::{ CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd, color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or, @@ -83,7 +84,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step", has_doc, set_props ), @@ -110,7 +111,7 @@ pub fn specs() -> Vec { "Move Rows", [], None, - "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", + "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). A row that goes into a Live Paint group from elsewhere joins its paths as livePaint.merge adds them, and the group is selected (paths, compound paths, groups of them and Live Paint groups; anything else is refused and nothing moves); a row that goes into or leaves a Live Paint group's paths makes the group's faces and edges again, keeping the paint of those that stay. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids} (a row that joined a Live Paint group is listed as the group)", has_doc, move_rows ), @@ -119,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -625,12 +626,22 @@ fn highlight(s: &mut Session, p: &Value) -> Result { "add" | "toggle" => {} other => return Err(bad(C, format!("mode is set, add or toggle, not `{other}`"))), } + // `rows` keeps the highlight order. With more than 8 ids, `held` holds the same rows as a set and + // answers each lookup; with fewer, each lookup searches `rows`. + let mut held: Option> = (ids.len() > 8).then(|| rows.iter().copied().collect()); let mut last = None; for id in ids { - if mode == "toggle" && rows.contains(&id) { + let has = held.as_ref().map_or_else(|| rows.contains(&id), |h| h.contains(&id)); + if mode == "toggle" && has { rows.retain(|r| *r != id); - } else if !rows.contains(&id) { + if let Some(h) = &mut held { + h.remove(&id); + } + } else if !has { rows.push(id); + if let Some(h) = &mut held { + h.insert(id); + } last = Some(id); } } @@ -651,6 +662,10 @@ fn set_props(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "no rows")); } + if let Some(v) = str_param(p, "name").filter(|v| !v.trim().is_empty()) { + let name = if xml_id { vectorcraft_doc::xml_id::to_object_name(v) } else { v.to_string() }; + super::buildcmds::check_part_name(&s.doc()?.doc, &ids, &name)?; + } s.edit("Layer Options", |d, sel| { for id in &ids { apply_options(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, p, xml_id); @@ -807,7 +822,15 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { if parent.is_some_and(|p| locked_within(d, p)) { return Err(EngineError::Other("the layer or group is locked".into())); } - let label = if copy { "Duplicate Rows" } else { "Move Rows" }; + // Rows that go into a Live Paint group join its paths, as Live Paint › Merge adds them. + let live_paint = LivePaintMove::plan(d, &ids, parent, copy)?; + let label = if live_paint.joins() { + "Merge Live Paint" + } else if copy { + "Duplicate Rows" + } else { + "Move Rows" + }; // Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the // Intertwine groups it leaves. let from: std::collections::HashMap> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect(); @@ -848,6 +871,7 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { } let placed: Vec<(NodeId, Option)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect(); super::intertwine::settle_members(d, &placed, &left)?; + let out = live_paint.finish(d, sel, &out)?; sel.prune(d); sel.deselect_uneditable(d); Ok(out) @@ -870,11 +894,14 @@ fn move_node(s: &mut Session, p: &Value) -> Result { if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } + let live_paint = LivePaintMove::plan(d, &[id], parent, false)?; + let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" }; let from = d.parent_of(id); let left = super::intertwine::groups_of(d, &[id]); - s.edit("Reorder", |d, sel| { + s.edit(label, |d, sel| { d.move_node(id, parent, index)?; super::intertwine::settle_members(d, &[(id, from)], &left)?; + live_paint.finish(d, sel, &[id])?; sel.prune(d); sel.deselect_uneditable(d); Ok(()) diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 5400e66728..81e73326fb 100644 --- a/crates/engine/src/cmd/layerpanel.rs +++ b/crates/engine/src/cmd/layerpanel.rs @@ -132,7 +132,7 @@ pub fn specs() -> Vec { "Locate Object", ["Window", "Layers"], None, - "{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", + "{id?, layersOnly?} (default: the frontmost selected object in the stacking order) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", has_doc, locate ), @@ -437,7 +437,8 @@ fn locate(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "layer.locate")?; let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?; let st = s.doc_mut()?; - let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; + // With no id, the frontmost selected object in the stacking order, whatever order it was selected in. + let id = id.or_else(|| st.selection.in_paint_order(&st.doc).last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; if layers_only { // Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself). diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 55c6612494..392d6340c6 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds; written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -634,7 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> /// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a /// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels -/// can't be read ([`readable`]). +/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image +/// is read with the clipping path it keeps ([`fileio::raster_image`]). fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index a2cb0e3f91..cfb87afdb3 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -214,6 +214,25 @@ fn spine_points_param(p: &Value, cmd: &str) -> Result> { list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(wrong)).collect() } +/// Whether linking handle `out` of spine point `index` at `q` would leave the blend's spine as it +/// is (false when the blend or the point is not there, for the edit to report it). +fn spine_link_unchanged(s: &Session, p: &Value, cmd: &str, index: usize, out: bool, q: Point) -> Result { + let id = match crate::cmd::object_param(p, "id", cmd)? { + Some(id) => Some(id), + None => selected_of(s, is_blend).first().copied(), + }; + let d = &s.doc()?.doc; + let Some(NodeKind::Blend { children, spec }) = id.and_then(|id| d.node(id)).map(|n| &n.kind) else { return Ok(false) }; + let Some((path, _)) = live::pin_spine(children, spec) else { return Ok(false) }; + Ok(path.subpaths.first().is_some_and(|sp| { + sp.anchors.get(index).is_some_and(|a| { + let mut linked = *a; + linked.link_handle(out, q, sp.has_segment(index, !out)); + linked == *a + }) + })) +} + pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { const C: &str = "object.blend.spine.moveAnchor"; let index = index_param(p, "anchor", C)?; @@ -225,15 +244,33 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(C, "handle must be in or out")), }; let independent = switch_or(p, "independent", false, C)?; + let link = switch_or(p, "link", false, C)?; let with = spine_points_param(p, C)?; // Any `with`, even an empty list, asks to move points, which a handle drag doesn't. if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) { return Err(bad(C, "`with` moves points, not a handle")); } + if link && independent { + return Err(bad(C, "`link` and `independent` cannot both be true")); + } + if link && handle.is_none() { + return Err(bad(C, "`link` places a handle: give `handle`")); + } + if link && let Some(out) = handle { + // A spine point the linked handles would leave as it is records no undo step. + if spine_link_unchanged(s, p, C, index, out, q)? { + return ok(); + } + } edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| { + let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out)); let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?; if let Some(out) = handle { - a.set_handle(out, q, independent); + if link { + a.link_handle(out, q, pull_out); + } else { + a.set_handle(out, q, independent); + } return Ok(()); } let delta = q - a.p; diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 79b2915aa0..991ebf103c 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Move Spine Point", [], None, - "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", + "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", has_doc, spine_move_anchor ), diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index defc405514..a1464ebcef 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -133,7 +133,7 @@ pub fn specs() -> Vec { "Create Object Mosaic…", ["Object"], None, - "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt; default the image's), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles coloured by the selected image's average tile colours → {id, tiles}", + "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors → {id, tiles, columns, rows}", has_image, object_mosaic ), @@ -970,7 +970,23 @@ pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> { } } -fn object_mosaic(s: &mut Session, p: &Value) -> Result { +/// What `object.createObjectMosaic` makes from its params: the image, the tile counts, the tiles' +/// placement, their size and spacing in image pixels, and the options. +struct MosaicPlan { + id: NodeId, + im: ImageObject, + cols: u32, + rows: u32, + xf: Affine, + tile: (f64, f64), + gap: (f64, f64), + gray: bool, + delete: bool, +} + +/// The mosaic `object.createObjectMosaic` would make from `p`, worked out without decoding the +/// image or changing the document. +fn mosaic_plan(s: &Session, p: &Value) -> Result { const C: &str = "object.createObjectMosaic"; let st = s.doc()?; let id = st @@ -980,28 +996,97 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { .copied() .find(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))) .ok_or_else(|| bad(C, "select an image"))?; - let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; - let blob = st.doc.images.get(&im.key).filter(|b| !b.bytes.is_empty()).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; - let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; - let cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32; - let rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32; + if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) { + return Err(bad(C, "the image has no embedded pixels")); + } + let mut cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32; + let mut rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32; let gray = switch_or(p, "gray", false, C)?; - let colors = vectorcraft_trace::mosaic(&raster, cols, rows); + let percentages = switch_or(p, "percentages", false, C)?; + // A side named "width" (true) or "height" (false), as `constrain` and `useRatio` take it. + let side = |key: &str, v: &Value, also: &str| match v.as_str() { + Some("width") => Ok(true), + Some("height") => Ok(false), + _ => Err(bad(C, format!("`{key}` must be one of {}", format_args!("\"width\", \"height\"{also} or null")))), + }; + let constrain = match p.get("constrain") { + None | Some(Value::Null) => None, + Some(v) => Some(side("constrain", v, "")?), + }; + // Use Ratio's kept side: true keeps Constrain Ratio's side (the width when it is left out). + let use_ratio = match p.get("useRatio") { + None | Some(Value::Null | Value::Bool(false)) => None, + Some(Value::Bool(true)) => Some(constrain.unwrap_or(true)), + Some(v) => Some(side("useRatio", v, ", true, false")?), + }; // Tiles in image space, placed by the image transform (scaled to a new size if asked). let b = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?; check_numbers(p, &["width", "height", "spacingX", "spacingY"], C)?; - let (nw, nh) = (f64_or(p, "width", b.width()).max(0.1), f64_or(p, "height", b.height()).max(0.1)); - let resize = Affine::translate(b.origin().to_vec2()) - * Affine::scale_non_uniform(nw / b.width().max(1e-9), nh / b.height().max(1e-9)) - * Affine::translate(-b.origin().to_vec2()); + let (bw, bh) = (b.width().max(1e-9), b.height().max(1e-9)); + // A size given (pt, or % of the image's) is from 0.1 to 1,000,000; one left out is the image's. + let size = |key: &str, base: f64| -> Result { + let Some(x) = p.get(key).and_then(Value::as_f64) else { return Ok(base) }; + let (min, max) = (0.1, 1_000_000.0); + if !(min..=max).contains(&x) { + return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + Ok(if percentages { base * x / 100.0 } else { x }) + }; + let (mut nw, mut nh) = (size("width", bw)?, size("height", bh)?); + // Constrain Ratio keeps the image's proportions: the named side leads and the other follows. + match constrain { + Some(true) => nh = nw * bh / bw, + Some(false) => nw = nh * bw / bh, + None => {} + } + // A size under 0.1 pt grows to 0.1 pt, in proportion while Constrain Ratio keeps it. A side + // Constrain Ratio works out above 1,000,000 pt shrinks to 1,000,000 pt, the other with it. + let (nw, nh) = match constrain { + Some(_) => { + let k = (0.1 / nw.min(nh)).max(1.0).min(1_000_000.0 / nw.max(nh)); + // Proportions over 10,000,000 to 1 leave no size with both sides within the range. + if nw.min(nh) * k < 0.1 * (1.0 - 1e-9) { + return Err(bad(C, "the image's proportions leave no size with both sides between 0.1 and 1000000 pt")); + } + (nw * k, nh * k) + } + None => (nw.max(0.1), nh.max(0.1)), + }; + let resize = Affine::translate(b.origin().to_vec2()) * Affine::scale_non_uniform(nw / bw, nh / bh) * Affine::translate(-b.origin().to_vec2()); let xf = resize * im.xf; - let (tw, th) = (im.width as f64 / cols as f64, im.height as f64 / rows as f64); - // Spacing is in points; convert to image pixels along each axis. + // Points per image pixel along each of the image's axes (the image may be turned). let ppx = (xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot().max(1e-9); let ppy = (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot().max(1e-9); - let (gx, gy) = ((f64_or(p, "spacingX", 0.0).max(0.0) / ppx).min(tw * 0.9), (f64_or(p, "spacingY", 0.0).max(0.0) / ppy).min(th * 0.9)); + let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0)); + let (iw, ih) = (im.width as f64, im.height as f64); + // Use Ratio: square tiles as drawn, spacing taken off, from the count on the kept side, + // measured along the image's axes. + match use_ratio { + Some(true) => rows = mosaic_square_count(cols, iw * ppx, ih * ppy, sx, sy), + Some(false) => cols = mosaic_square_count(rows, ih * ppy, iw * ppx, sy, sx), + None => {} + } + let (tw, th) = (iw / cols as f64, ih / rows as f64); + // Spacing is in points; convert to image pixels along each axis. + let gap = ((sx / ppx).min(tw * 0.9), (sy / ppy).min(th * 0.9)); let delete = switch_or(p, "deleteRaster", false, C)?; + Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, tile: (tw, th), gap, gray, delete }) +} + +/// The tile counts (columns, rows) `object.createObjectMosaic` would use with `p`, Use Ratio +/// included, without making the mosaic (the dialog's Use Ratio button shows them). +pub fn mosaic_counts(s: &Session, p: &Value) -> Result<(u32, u32)> { + mosaic_plan(s, p).map(|m| (m.cols, m.rows)) +} + +fn object_mosaic(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.createObjectMosaic"; + let MosaicPlan { id, im, cols, rows, xf, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?; + let blob = s.doc()?.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; + let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; + let colors = vectorcraft_trace::mosaic(&raster, cols, rows); let (gid, n) = s.edit("Create Object Mosaic", |d, sel| { let mut tiles = vec![]; for r in 0..rows { @@ -1039,7 +1124,32 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { sel.set([gid]); Ok((gid, n)) })?; - Ok(json!({ "id": gid.0, "tiles": n })) + Ok(json!({ "id": gid.0, "tiles": n, "columns": cols, "rows": rows })) +} + +/// The tile count along one side of an Object Mosaic whose tiles, as drawn, come closest to square +/// (Use Ratio): `kept` tiles span `kept_len` on the other side, and this side is `other_len` long. +/// Each tile is its cell less the gap on its side (`kept_gap`, `other_gap`), and a gap takes at +/// most 90% of a cell, as the tiles are drawn. Within 1..1000, the smaller count on a tie; all +/// lengths in points. +pub(crate) fn mosaic_square_count(kept: u32, kept_len: f64, other_len: f64, kept_gap: f64, other_gap: f64) -> u32 { + let drawn = |len: f64, n: u32, gap: f64| { + let cell = len / n.max(1) as f64; + cell - gap.max(0.0).min(cell * 0.9) + }; + let side = drawn(kept_len, kept, kept_gap); + if !(side.is_finite() && side > 0.0 && other_len.is_finite() && other_len > 0.0) { + return 1; + } + // A tile on this side shrinks as the count grows: find the first count whose tile is no wider + // than `side`, then take it or the count before it, whichever is closer. + let (mut lo, mut hi) = (1u32, 1000u32); + while lo < hi { + let mid = (lo + hi) / 2; + if drawn(other_len, mid, other_gap) > side { lo = mid + 1 } else { hi = mid } + } + let off = |n: u32| (drawn(other_len, n, other_gap) - side).abs(); + if lo > 1 && off(lo - 1) <= off(lo) { lo - 1 } else { lo } } fn polygon_path(pts: &[Point]) -> PathData { diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index ff0b22b31b..4250f3c377 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -371,16 +371,21 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result { } /// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn -/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one -/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is -/// inside it; → the group when paths were added. +/// in each Live Paint group that is `isolated` or holds it to that group, as `livePaint.merge` does, +/// innermost group first, one undo step per group ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]). +/// A group that `next` is or is inside is skipped, since isolation stays in it. → the outermost group +/// that paths were added to. fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option) -> Result> { let d = &s.doc()?.doc; - let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) }; - if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) { - return Ok(None); + let stays = next.and_then(|n| d.ancestry(n)).unwrap_or_default(); + let left: Vec = crate::cmd::buildcmds::isolated_live_paints(d, isolated).into_iter().filter(|g| !stays.contains(g)).collect(); + let mut added = None; + for g in left { + if crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)? { + added = Some(g); + } } - Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g)) + Ok(added) } pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 4be83d7da6..92f4744fea 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -250,7 +250,7 @@ pub fn specs() -> Vec { "Exit Isolation Mode", [], None, - "{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", + "{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same. Leaving a Live Paint group drawn in another isolated Live Paint group, and that group too, does this for each, innermost first, one undo step each", has_doc, exit_isolation ), @@ -259,7 +259,7 @@ pub fn specs() -> Vec { "Object Properties", [], None, - "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind", + "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already", has_doc, set_props ), diff --git a/crates/engine/src/cmd/object/props.rs b/crates/engine/src/cmd/object/props.rs index 54ad23eb2f..f576435fe0 100644 --- a/crates/engine/src/cmd/object/props.rs +++ b/crates/engine/src/cmd/object/props.rs @@ -65,6 +65,9 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result { }) }; let d = &s.doc()?.doc; + if let Some(v) = str_param(p, "name") { + crate::cmd::buildcmds::check_part_name(d, &ids, v)?; + } // A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label // for its kind of label, so a value a mark or label already has still replaces the one another left on the graph. let transparency = opacity.is_some() || blend.is_some(); diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index e8957691ec..7435f04a3a 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Attributes", [], None, - "{ids?|id?, item?, target?: \"object\"|\"contents\"} → {ids, overprintFill, overprintStroke, showCenter, imageMap: \"none\"|\"rectangle\"|\"polygon\", url, note, fillRule: \"nonZero\"|\"evenOdd\" (of the paths and compound paths in them), reversed (their subpaths run counter-clockwise on screen: Reverse Path Direction On), recentUrls: [newest first]} the Attributes panel's values for `ids` or the selection, overprint aimed as object.setOverprint aims; a value is null where they differ (or nothing has a fill, stroke or path)", + "{ids?|id?, item?, target?: \"object\"|\"contents\"} → {ids, overprintFill, overprintStroke, showCenter, imageMap: \"none\"|\"rectangle\"|\"polygon\", url, note, fillRule: \"nonZero\"|\"evenOdd\" (of the paths and compound paths in them), reversed (their subpaths run counter-clockwise on screen: Reverse Path Direction On), recentUrls: [newest first, at most 30]} the Attributes panel's values for `ids` or the selection, overprint aimed as object.setOverprint aims; a value is null where they differ (or nothing has a fill, stroke or path)", has_doc, |s, p| Ok(attributes(s, p)?.to_json()) ), diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 50e73f5a0d..8e7d7f7b0f 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -382,6 +382,7 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ ("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids"), + ("addon.pathtools.bridge", "radius", "gap"), ("links.unembed", "id", "ids"), ("links.unembed", "path", "folder"), ]; diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 0960e5ca28..f2a1b1d9f7 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool}", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false", has_doc, set_handle ), @@ -457,6 +457,9 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { let ai = index_opt(p, "anchor", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing anchor"))?; let out = str_param(p, "which") != Some("in"); let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?); + if switch_or(p, "link", false, "path.setHandle")? { + return link_handle(s, p, id, si, ai, out, pos); + } let independent = switch_or(p, "independent", false, "path.setHandle")?; // A handle already there, on an anchor already of the kind it would get, changes nothing and // records no undo step. The handle is compared directly: `set_handle` would recompute the @@ -476,6 +479,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { ok() } +/// `path.setHandle` with `link` (the Anchor Point tool's Alt-drag on a handle): the handle goes to +/// (x, y) and the anchor becomes smooth, its other handle turned in line at its own length. A +/// retracted other handle is pulled out to the moved handle's length when a segment leaves the +/// anchor on its side, and stays retracted at an open end. An anchor the edit would leave as it +/// is records no undo step. +fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out: bool, pos: Point) -> Result { + const C: &str = "path.setHandle"; + if switch_or(p, "independent", false, C)? { + return Err(bad(C, "`link` and `independent` cannot both be true")); + } + if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) { + return Err(bad(C, "x and y must be finite")); + } + if s.script_running() { + return Err(EngineError::Busy); + } + let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| { + sp.anchors.get(ai).is_some_and(|a| { + let mut linked = *a; + linked.link_handle(out, pos, sp.has_segment(ai, !out)); + linked == *a + }) + }); + if unchanged { + return ok(); + } + s.edit("Reshape", |d, _| { + let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + let pull_out = sp.has_segment(ai, !out); + let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + a.link_handle(out, pos, pull_out); + Ok(()) + })?; + ok() +} + /// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point /// tool's Shift-drag). fn move_anchor(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/place/docx.rs b/crates/engine/src/cmd/place/docx.rs index 804e3fd6ae..6766b67c7c 100644 --- a/crates/engine/src/cmd/place/docx.rs +++ b/crates/engine/src/cmd/place/docx.rs @@ -171,8 +171,6 @@ fn parse(xml: &str, name: &str, cmd: &str) -> Result { craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")), _ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")), })?; - crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits) - .map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?; Ok(doc) } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 80c8e7f2bf..5a10ae3d9c 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -88,6 +88,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.type.textTweaker", "addon.units.convert", "addon.units.selectionSize", + "app.toast", "appearance.addEffect", "appearance.addFill", "appearance.addStroke", @@ -177,6 +178,7 @@ pub(super) const ALLOWED: &[&str] = &[ "edit.duplicate", "edit.findNext", "edit.findReplace", + "edit.replaceMatch", "effect.apply", "effect.deferredStatus", "effect.duplicate", @@ -555,6 +557,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.update", "shape.arc", "shape.circleThroughPoints", + "shape.editFlare", "shape.ellipse", "shape.flare", "shape.line", @@ -689,6 +692,7 @@ pub(super) const ALLOWED: &[&str] = &[ "type.pathOptions", "type.resetHorizontalScale", "type.resetTracking", + "type.retype", "type.ruby", "type.scaleTextAttributes", "type.size.decrease", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 774c450065..491284bb23 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -157,6 +157,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool), p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool), p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool), + p!("holdShortcuts", "General", "Options", "Hold Shortcuts", bool), + p!("keyHoldDelay", "General", "Options", "Hold Shortcut Delay", num(0.2, 1.0, "s")), p!("boundingBoxWhileMovingAndDrawing", "General", "Options", "Show Bounding Box While Moving and Drawing", bool), // Selection & Anchor Display p!("selectionTolerance", "Selection & Anchor Display", "Selection", "Tolerance", num(1.0, 8.0, "px")), diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index cb179148cc..1c3acf4e73 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -1680,12 +1680,18 @@ fn apply(s: &mut Session, p: &Value) -> Result { Some(Value::Array(cs)) => Some(cs), Some(_) => return Err(bad(C, "`groupColors` must be an array")), }; - // A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch - // at its place its color, without the Global Adjust. - let own: Vec> = match group { - Some(g) => { - s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default() - } + // The places of groupColors are those of the group's color swatches: a gradient, pattern or + // None swatch keeps its place and paint. A null removes the color swatch at its place, and + // "keep" leaves it its color, without the Global Adjust. + let own: Vec = match group { + Some(g) => s + .doc()? + .doc + .swatch_groups + .iter() + .find(|x| x.name == g) + .map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).collect()) + .unwrap_or_default(), None => vec![], }; let new: Vec> = match group_colors { @@ -1694,12 +1700,8 @@ fn apply(s: &mut Session, p: &Value) -> Result { .enumerate() .map(|(i, v)| match v { Value::Null => Ok(None), - // Past the group's swatches it adds nothing. - Value::String(k) if k == "keep" => match own.get(i) { - Some(Some(c)) => Ok(Some(*c)), - Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))), - None => Ok(None), - }, + // Past the group's color swatches it adds nothing. + Value::String(k) if k == "keep" => Ok(own.get(i).copied()), v => color_value(v) .map(|c| adjust.apply(c)) .map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))) @@ -1747,6 +1749,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { .map(|g| { g.swatches .iter() + .filter(|w| w.paint.color().is_some()) .zip(&new) .filter(|(w, _)| w.global && !w.is_reserved()) .filter_map(|(w, c)| Some((w, (*c)?))) @@ -1766,7 +1769,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { .collect(); map.converted.set(false); let changed = keeping_series_paint(d, &ids, |d| Ok(Recolor::with_links(scope, &f, &lf).run(d, &ids)))?; - let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, rename, C)).transpose()?; + let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, true, rename, C)).transpose()?; super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; // Rewriting the group's swatches can change the colors of art linked to them, left out or // not, and of the patterns it uses. Art that only loses its link keeps its colors and is diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs new file mode 100644 index 0000000000..23774aaaa7 --- /dev/null +++ b/crates/engine/src/cmd/retype.rs @@ -0,0 +1,619 @@ +//! Type › Retype (#4934), phase 1: outlined text whose glyph shapes are glyphs of a font the app +//! has becomes live point text again, in that font and size, at the same baseline. +//! +//! Behaviour follows the public description of Illustrator's Retype +//! (, +//! ): +//! select outlined text and Retype finds the fonts that match it, from the fonts on the device among +//! others, for use as live text. Illustrator ranks candidate fonts in a panel; this phase is local +//! and exact instead, and sets the text itself, as #4934 asks. Each selected glyph shape (a path or compound +//! path, inside groups too) is compared with the glyphs of the candidate fonts +//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched +//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object +//! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as +//! they are and are reported. Near matches (another version of the font, simplified outlines, +//! merged glyphs) and images are phase 2. + +use std::f64::consts::{PI, TAU}; +use std::sync::Arc; + +use kurbo::{BezPath, Point, Vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::{GlyphMatch, RetypeIndex}; + +use super::edit::selected_roots; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; + +/// At most this many shapes are compared. +const MAX_PIECES: usize = 2048; +/// Groups deeper than this are not looked into. +const MAX_DEPTH: usize = 16; +/// Extra families named by `fonts`. +const MAX_FONT_PARAMS: usize = 32; + +pub fn specs() -> Vec { + vec![cmd!( + "type.retype", + "Retype", + ["Type"], + None, + "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", + has_selected_path, + retype + )] +} + +/// A shape to match: a path or compound path, in document space. +struct Piece { + id: NodeId, + /// The group or layer holding it: glyphs of different groups, which may composite + /// differently, never share a line. + parent: Option, + /// Other art (not retyped) lies between it and the shape before it, so the type after that + /// art must stay painted after it: the line ends here. + after_barrier: bool, + path: BezPath, + appearance: Appearance, + /// The shape's own transparency, which the new type takes. + opacity: f32, + blend: vectorcraft_color::BlendMode, + /// The shape has what type cannot take (its own opacity mask, more than one fill or stroke, + /// effects, a brush, width profile or arrowheads): it stays an outline. + keeps_outline: bool, +} + +/// The shapes in `n` (held by `parent`), in paint order. `barrier` is set when art that is not a +/// shape lies before the next one; it starts set for a root that does not follow the last root. +/// `truncated` is set when shapes past [`MAX_PIECES`] or [`MAX_DEPTH`] were left out. +fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, truncated: &mut bool, out: &mut Vec) { + if out.len() >= MAX_PIECES || depth > MAX_DEPTH { + *barrier = true; + *truncated = true; + return; + } + // Hidden and locked art is left as it is: a hidden glyph must not come back as visible type. + if !n.visible || n.locked { + *barrier = true; + return; + } + let piece = |path: BezPath, after_barrier: bool| Piece { + id: n.id, + parent, + after_barrier, + path, + appearance: (*n.appearance).clone(), + opacity: n.opacity, + blend: n.blend, + keeps_outline: n.extras().mask.is_some() || !type_can_paint(&n.appearance), + }; + match &n.kind { + NodeKind::Group { children, clip: false } => { + for c in children { + collect(c, Some(n.id), depth + 1, barrier, truncated, out); + } + } + // Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one. + NodeKind::Path { path, clipping: false, guide: false, .. } if path.is_closed() => out.push(piece(path.to_bezpath(), std::mem::take(barrier))), + NodeKind::Compound { children, .. } => { + let mut path = BezPath::new(); + for c in children { + match &c.kind { + // A hidden or locked path keeps its whole compound as it is. + NodeKind::Path { path: p, .. } if p.is_closed() && c.visible && !c.locked => path.extend(p.to_bezpath()), + _ => { + *barrier = true; + return; + } + } + } + out.push(piece(path, std::mem::take(barrier))); + } + // Live type, images, clip groups and the rest stay, and the type after them stays after them. + _ => *barrier = true, + } +} + +/// Can type's character style paint `ap` as it is: a basic appearance (at most one fill and one +/// stroke, no effects, no item opacity or blend), with a plain stroke? +fn type_can_paint(ap: &Appearance) -> bool { + ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none()) +} + +/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. +fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { + let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + for r in &t.runs { + if !families.contains(&r.style.font_family) && families.len() < vectorcraft_text::retype::MAX_FACES { + families.push(r.style.font_family.clone()); + } + } + } + }); + let cap = vectorcraft_text::retype::MAX_FACES; + let mut faces = vec![]; + 'families: for f in &families { + for style in db.styles(f) { + // No more faces are loaded than the index takes. + if faces.len() >= cap { + break 'families; + } + if let Some(face) = db.face(f, &style) + && !faces.iter().any(|k: &Arc| k.id() == face.id()) + { + faces.push(face); + } + } + } + for face in db.loaded_faces() { + if faces.len() >= cap { + break; + } + if !faces.iter().any(|k| k.id() == face.id()) { + faces.push(face); + } + } + faces +} + +/// One line of retyped glyphs. +struct Line { + pieces: Vec, + /// What each piece matched, as `pieces`. + matches: Vec, + /// Every glyph the first piece fits, while the line holds only it: the next glyph may tell + /// which one it is (see [`join`]). + first_cands: Vec, + text: String, + face: Arc, + scale: f64, + angle: f64, + origin: Point, + end: Point, + appearance: Appearance, + parent: Option, + opacity: f32, + blend: vectorcraft_color::BlendMode, +} + +impl Line { + fn dir(&self) -> Vec2 { + Vec2::new(self.angle.cos(), self.angle.sin()) + } + + /// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same + /// font, size and turn, on its baseline, after its end)? + fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool { + let size = self.scale * self.face.units_per_em(); + let d = m.origin - self.origin; + let dir = self.dir(); + let across = d.cross(dir).abs(); + pc.parent == self.parent + && pc.appearance == self.appearance + && pc.opacity == self.opacity + && pc.blend == self.blend + && m.face.id() == self.face.id() + // One size and turn for the whole line: the type sets every glyph at the first one's. + && (m.scale - self.scale).abs() <= self.scale * 1e-4 + // Wrapped: type turned 180° has angles near +π and −π. + && ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + && across < size * 0.05 + && (m.origin - self.end).dot(dir) > -size * 0.25 + } + + fn push(&mut self, id: NodeId, m: &GlyphMatch) { + // A gap wider than half a space before the glyph is spaces the outlines left no shape for. + let dir = self.dir(); + let gap = (m.origin - self.end).dot(dir); + let space = space_advance(&self.face) * self.scale; + if space > 0.0 && gap > space * 0.5 { + let n = ((gap / space).round() as usize).clamp(1, 64); + self.text.extend(std::iter::repeat_n(' ', n)); + } + self.text.push(m.ch); + self.pieces.push(id); + self.matches.push(m.clone()); + self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale); + } + + /// The line of this one's glyphs `from..to`, with its group, paint and transparency. + fn part(&self, from: usize, to: usize) -> Option { + let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?); + let (first, m) = (ids.first()?, ms.first()?); + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + let mut l = Line { + pieces: vec![*first], + matches: vec![m.clone()], + first_cands: vec![], + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: self.appearance.clone(), + parent: self.parent, + opacity: self.opacity, + blend: self.blend, + }; + for (id, m) in ids.iter().zip(ms).skip(1) { + l.push(*id, m); + } + Some(l) + } + + /// The point type that sets this line. + fn text_object(&self, system_layout: bool) -> TextObject { + let style = CharStyle { + font_family: self.face.family.clone(), + font_style: self.face.style.clone(), + // The version that matched, when two of the family and style are loaded. + font_version: (!self.face.version.is_empty()).then(|| self.face.version.clone()), + // Each outlined glyph was drawn on its own; a ligature would draw another shape. + features: vec!["-liga".into()], + size: self.scale * self.face.units_per_em(), + fill: self.appearance.fill_paint(), + stroke: self.appearance.stroke_paint(), + stroke_width: self.appearance.stroke_width(), + ..Default::default() + }; + let mut style = style; + if let Some(st) = self.appearance.stroke() { + style.stroke_cap = st.cap; + style.stroke_join = st.join; + style.stroke_miter_limit = st.miter_limit; + style.stroke_dash = st.dash.clone(); + style.stroke_align = st.align; + } + let mut t = TextObject::point(self.origin, &self.text, style); + if self.angle != 0.0 { + t.xf *= kurbo::Affine::rotate(self.angle); + } + t.para = super::create::new_type_para(); + t.system_layout = system_layout; + super::typecmd::refresh_bounds(&mut t); + t + } + + /// The first of this line's glyphs its type does not draw as the outlines did: another glyph + /// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, + /// more space than whole spaces make); `None` when the type draws every glyph in its place. + fn first_mismatch(&self, t: &TextObject) -> Option { + let lay = vectorcraft_text::layout(FontDb::global(), t); + let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); + let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01); + for (k, m) in self.matches.iter().enumerate() { + let Some(g) = drawn.next() else { return Some(k) }; + let at = t.xf * (g.xf * Point::ORIGIN); + if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { + return Some(k); + } + } + // Ink the outlines did not have: the last glyph is where it went wrong. + drawn.next().map(|_| self.matches.len().saturating_sub(1)) + } +} + +/// `lines` checked against their own layout: a line splits where its type stops drawing the +/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). +/// The glyphs laid out are bounded by a multiple of the number of glyphs. +fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) -> Vec { + // Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines. + let mut budget = lines.iter().map(|l| l.pieces.len()).sum::().saturating_mul(16).saturating_add(256); + let mut todo: std::collections::VecDeque = lines.into(); + let mut out = vec![]; + while let Some(l) = todo.pop_front() { + let n = l.pieces.len(); + // The line's type is laid out over a window from its start that doubles while the type + // draws the window's glyphs as the outlines do, so finding where it stops costs about + // twice the glyphs before that point, not the whole rest of the line each time. + let mut w = 8usize; + loop { + let e = n.min(w); + let Some(part) = l.part(0, e) else { break }; + let Some(left) = budget.checked_sub(e) else { + // Unchecked glyphs stay outlines. + unmatched.extend(l.pieces.iter().copied()); + break; + }; + budget = left; + match part.first_mismatch(&part.text_object(system_layout)) { + // The whole line is drawn as it was: one object. + None if e == n => { + out.push(part); + break; + } + None => w = w.saturating_mul(2), + // The first glyph on its own may still be drawn as it was (a contextual form + // changed it in the line); else it stays an outline. Checked again either way. + Some(0) if n > 1 => { + todo.extend_front_parts(&l, [(0, 1), (1, n)]); + break; + } + Some(0) => { + unmatched.extend(l.pieces.first().copied()); + break; + } + // The glyphs before the mismatch, then the rest, each checked as a line of its + // own: the type before the mismatch may draw otherwise without what follows it (a + // font can place a glyph by the glyph after it). + Some(k) => { + todo.extend_front_parts(&l, [(0, k), (k, n)]); + break; + } + } + } + } + out +} + +/// Puts parts of a line at the front of the work list, in order. +trait FrontParts { + fn extend_front_parts(&mut self, l: &Line, ranges: [(usize, usize); N]); +} + +impl FrontParts for std::collections::VecDeque { + fn extend_front_parts(&mut self, l: &Line, ranges: [(usize, usize); N]) { + for (a, b) in ranges.into_iter().rev() { + if let Some(p) = l.part(a, b) { + self.push_front(p); + } + } + } +} + +fn space_advance(face: &vectorcraft_text::FontFace) -> f64 { + face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0) +} + +/// Add shape `pc` to line `l` when one of its candidate glyphs `cands`, in one of its poses, +/// continues it (one shape can be several glyphs, and a glyph that looks the same turned fits in +/// more than one pose). A line of one shape may turn to another of that shape's candidates to take +/// the next one: an L or a turned L half round, an I upright or upside down, and the glyph after it +/// tells which. Whether it was added. +fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool { + let fits = |l: &Line| cands.iter().flat_map(|c| c.poses()).find(|mp| l.continues(pc, mp)); + if let Some(mp) = fits(l) { + l.push(pc.id, &mp); + return true; + } + let (Some(id), [current]) = (l.pieces.first().copied(), l.matches.as_slice()) else { return false }; + let current = current.clone(); + let others: Vec = l + .first_cands + .iter() + .flat_map(|c| c.poses()) + .filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle)) + .collect(); + for fp in others { + let mut turned = reposed(l, id, &fp); + if let Some(mp) = fits(&turned) { + turned.push(pc.id, &mp); + *l = turned; + return true; + } + } + false +} + +/// Line `l`'s group, paint and transparency with glyph `m` (shape `id`) alone on it. +fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + Line { + pieces: vec![id], + matches: vec![m.clone()], + first_cands: l.first_cands.clone(), + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: l.appearance.clone(), + parent: l.parent, + opacity: l.opacity, + blend: l.blend, + } +} + +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`). +fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { + let m = cands.first()?; + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + Some(Line { + pieces: vec![pc.id], + matches: vec![m.clone()], + first_cands: cands.to_vec(), + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: pc.appearance.clone(), + parent: pc.parent, + opacity: pc.opacity, + blend: pc.blend, + }) +} + +fn retype(s: &mut Session, p: &Value) -> Result { + const C: &str = "type.retype"; + let fonts: Vec = match p.get("fonts") { + None | Some(Value::Null) => vec![], + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? + } + Some(_) => return Err(bad(C, "fonts must be a list of family names")), + }; + let roots = selected_roots(s)?; + let db = FontDb::global(); + let system_layout = s.doc()?.doc.setup.system_layout; + let (lines, unmatched, truncated) = { + let d = &s.doc()?.doc; + let mut pieces = vec![]; + let mut truncated = false; + let mut last: Option<(Option, usize)> = None; + // Carried across roots: a selected root that yields no shape (live type, an open path) still + // ends the line. + let mut barrier = true; + for r in &roots { + let Some(n) = d.node(*r) else { continue }; + let parent = d.parent_of(*r); + let idx = d.position(*r).map(|(_, i, _)| i); + // A root right after the last one, in the same parent, continues its lines; unselected + // art between two roots is a barrier. + if !matches!((last, idx), (Some((p, i)), Some(j)) if p == parent && i + 1 == j) { + barrier = true; + } + last = idx.map(|i| (parent, i)); + collect(n, parent, 0, &mut barrier, &mut truncated, &mut pieces); + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + // Only glyphs with a selected shape's key (segments per contour) can match one: the others are + // not sampled. + let wanted: std::collections::BTreeSet = + pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); + // Nothing to match (every shape stays an outline): no font is read. + let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) }; + let found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); + // The face most shapes match, so a glyph several fonts share is set in the same font as + // the glyphs around it. + let mut votes: Vec<(u32, usize)> = vec![]; + for ms in &found { + // Each shape votes once for each face it fits. + let mut faces: Vec = ms.iter().map(|m| m.face.id()).collect(); + faces.sort_unstable(); + faces.dedup(); + for f in faces { + match votes.iter_mut().find(|(v, _)| *v == f) { + Some(v) => v.1 += 1, + None => votes.push((f, 1)), + } + } + } + let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1); + let mut lines: Vec = vec![]; + let mut unmatched = vec![]; + // An unmatched shape between glyphs ends the line: the type after it is painted after it. + let mut open = false; + for (pc, ms) in pieces.iter().zip(&found) { + if pc.after_barrier { + open = false; + } + // The shape's candidates in the face most shapes fit (the first such face, as the + // matches come upright and closest first). + let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + if cands.is_empty() { + unmatched.push(pc.id); + open = false; + continue; + } + let joined = match lines.last_mut() { + Some(l) if open => join(l, pc, &cands), + _ => false, + }; + if !joined { + lines.extend(new_line(pc, &cands)); + } + open = true; + } + // A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn + // art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is + // what was asked for. Lone means alone on its baseline as the outlines lie, before the + // layout check splits lines (tracking and manual kerning split them glyph by glyph). + let lone_pieces: std::collections::HashSet = + lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect(); + let mut lines = verified(lines, system_layout, &mut unmatched); + if pieces.len() > 1 { + lines.retain(|l| { + let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); + if lone { + unmatched.extend(l.pieces.iter().copied()); + } + !lone + }); + } + (lines, unmatched, truncated) + }; + if lines.is_empty() { + return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); + } + let made = s.edit("Retype", |d, sel| { + let mut ids = vec![]; + let mut emptied = vec![]; + for l in &lines { + let Some(first) = l.pieces.first() else { continue }; + let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?; + let t = l.text_object(system_layout); + let id = d.alloc_id(); + let mut node = Node::new(id, NodeKind::Text(Box::new(t))); + // The glyphs' own transparency (the group's, kept, still applies over it). + node.opacity = l.opacity; + node.blend = l.blend; + d.insert(par, idx, node)?; + for pc in &l.pieces { + if let Some((Some(parent), _, _)) = d.position(*pc) { + emptied.push(parent); + } + d.remove(*pc)?; + } + ids.push(id); + } + // A group left holding only the new type (Create Outlines' group) gives way to it, unless + // the group has transparency, effects, a mask or a name of its own, which then keep + // applying to the type inside it. A group left empty goes. + emptied.sort_unstable(); + emptied.dedup(); + for g in emptied { + let Some(n) = d.node(g) else { continue }; + let NodeKind::Group { children, clip: false } = &n.kind else { continue }; + let plain = n.opacity == 1.0 + && n.blend == vectorcraft_color::BlendMode::Normal + && *n.appearance == Appearance::default() + && n.name.is_none() + // Its mask, Attributes note and the rest of what few objects have stay with it. + && { + let mut ex = n.extras().clone(); + ex.type_outlines = false; + ex == vectorcraft_doc::NodeExtras::default() + } + // Isolation and knockout change how the group composites its type. + && !n.isolate + && n.knockout == vectorcraft_doc::Knockout::default() + && !n.knockout_shape; + let only_type = children.iter().all(|c| ids.contains(&c.id)); + if children.is_empty() { + d.remove(g)?; + } else if plain && only_type { + let kids: Vec> = children.clone(); + let (par, idx, _) = d.position(g).ok_or(EngineError::NoNode(g))?; + d.remove(g)?; + for (i, k) in kids.into_iter().enumerate() { + d.insert(par, idx + i, (*k).clone())?; + } + } + } + let mut keep: Vec = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect(); + keep.extend(&ids); + sel.set(keep); + Ok(ids) + })?; + Ok(json!({ + "ids": made.iter().map(|i| i.0).collect::>(), + "texts": lines.iter().map(|l| l.text.clone()).collect::>(), + "fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::>(), + "unmatched": unmatched.iter().map(|i| i.0).collect::>(), + "truncated": truncated, + })) +} + +#[cfg(test)] +#[path = "retype_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs new file mode 100644 index 0000000000..d691ab34fa --- /dev/null +++ b/crates/engine/src/cmd/retype_tests.rs @@ -0,0 +1,539 @@ +use serde_json::json; +use vectorcraft_doc::{NodeId, NodeKind, TextObject}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +/// Point text, outlined: the id of the outlines' group. +fn outlined(s: &mut Session, p: serde_json::Value) -> u64 { + let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap() +} + +fn text_of(s: &Session, id: u64) -> TextObject { + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text object") }; + (**t).clone() +} + +fn near(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol +} + +#[test] +fn outlined_point_text_retypes_to_the_same_text_font_size_and_place() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Retype me, 42!", "size": 36, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Retype me, 42!"]), "{r}"); + assert_eq!(r["unmatched"], json!([])); + let id = r["ids"][0].as_u64().unwrap(); + let t = text_of(&s, id); + assert_eq!(t.plain_text(), "Retype me, 42!"); + let st = t.first_style(); + assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Source Sans 3", "Regular")); + assert!(near(st.size, 36.0, 0.01), "size {}", st.size); + let o = t.xf.translation(); + assert!(near(o.x, 40.0, 0.01) && near(o.y, 100.0, 0.01), "baseline start {o:?}"); + // The outlines are gone, in one undo step that brings them back. + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g)).is_none(), "the emptied group goes"); + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g)).is_some() && d.node(NodeId(id)).is_none()); +} + +#[test] +fn turned_bold_and_serif_type_keeps_its_font_and_angle() { + let mut s = session(); + let a = outlined(&mut s, json!({"x": 100, "y": 200, "text": "Bold", "size": 24, "font": "Source Sans 3", "style": "Bold", "rotation": 30})); + let b = outlined(&mut s, json!({"x": 300, "y": 80, "text": "Serif", "size": 18, "font": "Source Serif 4", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Bold", "Serif"]), "{r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let bold = text_of(&s, ids[0]); + assert_eq!(bold.first_style().font_style, "Bold"); + assert!(near(bold.first_style().size, 24.0, 0.01)); + // text.create turns as kurbo does: compare the turn the new type has with the old one's. + let turned = kurbo::Affine::translate((100.0, 200.0)) * vectorcraft_geom::rotate_deg(30.0); + for (x, y) in bold.xf.as_coeffs().iter().zip(turned.as_coeffs()) { + assert!(near(*x, y, 1e-3), "{:?} vs {:?}", bold.xf, turned); + } + let serif = text_of(&s, ids[1]); + assert_eq!(serif.first_style().font_family, "Source Serif 4"); + assert!(near(serif.first_style().size, 18.0, 0.01)); +} + +#[test] +fn a_drawn_shape_is_reported_and_left_alone() { + let mut s = session(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected shape matches"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); + // With outlines that would match, a bad `fonts` is refused for itself, and nothing changes. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] { + let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string(); + assert!(e.contains("fonts must be a list of family names"), "{e}"); + } + assert!(s.doc().unwrap().doc == before); +} + +#[test] +fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Mix", "size": 30})); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g, rect]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Mix"])); + assert_eq!(r["unmatched"], json!([rect])); + let d = &s.doc().unwrap().doc; + assert!(matches!(d.node(NodeId(rect)).unwrap().kind, NodeKind::Path { .. }), "the rectangle stays"); +} + +#[test] +fn two_words_keep_their_space() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "two words", "size": 20})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["two words"])); +} + +#[test] +fn craft_fonts_glyphs_retype_too() { + let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + }; + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "漢字です", "size": 20, "font": f.family, "style": f.style})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"fonts": [f.family]})).unwrap(); + assert_eq!(r["texts"], json!(["漢字です"]), "{r}"); + assert_eq!(r["fonts"][0]["family"], json!(f.family)); +} + +fn children_of(s: &Session, g: u64) -> Vec { + s.doc().unwrap().doc.node(NodeId(g)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect() +} + +#[test] +fn a_shape_between_glyphs_ends_the_line_so_paint_order_holds() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 50})).unwrap()["id"].as_u64().unwrap(); + // The rectangle goes between A and B, inside the outlines' group. + s.edit("test", |d, _| { + let n = d.node(NodeId(rect)).unwrap().clone(); + d.remove(NodeId(rect))?; + d.insert(Some(NodeId(g)), 1, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "{r}"); + assert_eq!(r["unmatched"], json!([rect])); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(children_of(&s, g), vec![ids[0], rect, ids[1]], "A under the rectangle, B over it"); +} + +#[test] +fn glyphs_of_different_groups_and_transparency_stay_apart() { + let mut s = session(); + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20})); + let b = outlined(&mut s, json!({"x": 120, "y": 100, "text": "ed", "size": 20})); + let first_d = children_of(&s, b)[1]; + s.edit("test", |d, _| { + d.node_mut(NodeId(b)).unwrap().opacity = 0.5; + d.node_mut(NodeId(first_d)).unwrap().opacity = 0.25; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab", "e", "d"]), "same baseline, other group; d has its own opacity: {r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(a)).is_none(), "a plain group gives way to its type"); + assert_eq!(d.node(NodeId(b)).unwrap().opacity, 0.5, "the half-transparent group stays"); + assert_eq!(children_of(&s, b), vec![ids[1], ids[2]]); + assert_eq!(s.doc().unwrap().doc.node(NodeId(ids[2])).unwrap().opacity, 0.25, "the glyph's own opacity carries over"); +} + +#[test] +fn live_type_between_glyphs_ends_the_line_too() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap(); + s.edit("test", |d, _| { + let n = d.node(NodeId(live)).unwrap().clone(); + d.remove(NodeId(live))?; + d.insert(Some(NodeId(g)), 1, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "{r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(children_of(&s, g), vec![ids[0], live, ids[1]], "B stays over the live type"); + let t = text_of(&s, ids[0]); + assert!(t.first_style().features.iter().any(|f| f == "-liga"), "glyphs drawn one by one: no ligatures"); +} + +#[test] +fn an_open_path_along_a_glyph_is_not_a_glyph() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "I", "size": 40})); + s.edit("test", |d, _| { + let glyph = d.node(NodeId(g)).unwrap().children().unwrap()[0].id; + for sp in &mut d.node_mut(glyph).unwrap().path_data_mut().unwrap().subpaths { + sp.closed = false; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); +} + +#[test] +fn live_type_selected_between_loose_glyphs_still_ends_the_line() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap(); + let (a, b) = (children_of(&s, g)[0], children_of(&s, g)[1]); + // A, the live type and B as siblings in the layer, as Ungroup leaves them. + s.edit("test", |d, _| { + let (par, idx, _) = d.position(NodeId(g)).unwrap(); + let live_n = d.node(NodeId(live)).unwrap().clone(); + let (an, bn) = (d.node(NodeId(a)).unwrap().clone(), d.node(NodeId(b)).unwrap().clone()); + d.remove(NodeId(live))?; + d.remove(NodeId(g))?; + d.insert(par, idx, an)?; + d.insert(par, idx + 1, live_n)?; + d.insert(par, idx + 2, bn)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a, live, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "the selected live type between them ends the line: {r}"); +} + +#[test] +fn glyphs_selected_inside_groups_join_only_their_siblings() { + let mut s = session(); + let g1 = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20})); + let g2 = outlined(&mut s, json!({"x": 70, "y": 100, "text": "ed", "size": 20})); + let (a, b, c) = (children_of(&s, g1)[0], children_of(&s, g1)[1], children_of(&s, g2)[0]); + s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab", "e"]), "a and b are siblings; e is in another group: {r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g2)).is_some(), "d's group stays with c's type and d in it"); +} + +#[test] +fn tracked_type_splits_where_its_spacing_cannot_be_set_again() { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "abe", "size": 30})).unwrap()["id"].as_u64().unwrap(); + // Less than half a space: no whole number of spaces makes up the gap (0.4 em would be two + // spaces in this font, and the outlines cannot tell those apart from tracking). + s.execute("text.setRangeStyle", &json!({"id": id, "start": 1, "end": 3, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), "abe", "{r}"); + assert!(texts.len() > 1, "the tracked glyphs are set where the outlines are, not where untracked type puts them: {r}"); + assert_eq!(r["unmatched"], json!([])); +} + +#[test] +fn a_masked_glyph_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default()); + d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "{r}"); + assert_eq!(r["unmatched"], json!([a])); + assert!(s.doc().unwrap().doc.node(NodeId(a)).unwrap().extras().mask.is_some(), "A keeps its mask"); +} + +#[test] +fn shapes_past_the_limits_are_reported_as_left_out() { + let mut s = session(); + let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let deep = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 40})); + // B, deeper than Retype looks. + s.edit("test", |d, _| { + let (par, idx, _) = d.position(NodeId(deep)).unwrap(); + let mut n = d.node(NodeId(deep)).unwrap().clone(); + d.remove(NodeId(deep))?; + for _ in 0..20 { + n = vectorcraft_doc::Node::group(d.alloc_id(), vec![std::sync::Arc::new(n)]); + } + let wrapper = n.id.0; + d.insert(par, idx, n)?; + Ok(wrapper) + }) + .map(|w| s.execute("select.set", &json!({"ids": [top, w]})).unwrap()) + .unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A"])); + assert_eq!(r["truncated"], json!(true), "{r}"); +} + +#[test] +fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let n = d.node_mut(NodeId(a)).unwrap(); + let mut ap = (*n.appearance).clone(); + let fill = ap.items.iter().find(|i| i.is_fill()).unwrap().clone(); + ap.items.push(fill); + n.appearance = ap.into(); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); + assert_eq!(r["unmatched"], json!([a])); +} + +#[test] +fn a_hidden_or_locked_glyph_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ABD", "size": 40})); + let k = children_of(&s, g); + s.edit("test", |d, _| { + d.node_mut(NodeId(k[0])).unwrap().visible = false; + d.node_mut(NodeId(k[2])).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(!d.node(NodeId(k[0])).unwrap().visible, "A stays a hidden outline"); + assert!(d.node(NodeId(k[2])).unwrap().locked, "D stays a locked outline"); +} + +#[test] +fn an_isolated_or_knockout_group_keeps_its_type_inside() { + for case in ["isolate", "knockout", "knockout_shape"] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + s.edit("test", |d, _| { + let n = d.node_mut(NodeId(g)).unwrap(); + match case { + "isolate" => n.isolate = true, + "knockout" => n.knockout = vectorcraft_doc::Knockout::On, + _ => n.knockout_shape = true, + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let id = r["ids"][0].as_u64().unwrap(); + assert_eq!(children_of(&s, g), vec![id], "{case}: the group stays, holding the type"); + } +} + +#[test] +fn type_turned_half_round_stays_one_object() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "Upside", "size": 30, "rotation": 180})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Upside"]), "{r}"); +} + +#[test] +fn a_drawn_dot_or_bar_beside_type_stays_art() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); + // A bar that is exactly a hyphen of the font, somewhere else: the worst case. + let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50})); + s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["AB"]), "{r}"); + let un = r["unmatched"].as_array().unwrap(); + assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}"); + // Selected on its own, the hyphen is what was asked for. + s.execute("select.set", &json!({"ids": [bar]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["-"]), "{r}"); +} + +/// How long Retype takes with a large CJK face to match against (run with `--ignored +/// --nocapture`; skips when no such face is installed). Not a pass/fail budget: it prints. +#[test] +#[ignore = "timing: needs an installed CJK font"] +fn timing_with_a_large_cjk_face() { + let db = vectorcraft_text::FontDb::global(); + let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f)) + else { + eprintln!("skipped: no large CJK font installed"); + return; + }; + let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap(); + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 80, "text": "漢字のテスト ABC", "size": 24, "font": family, "style": face.style})); + for run in ["cold", "warm"] { + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap(); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + eprintln!("{run}: Retype with {family} ({} encoded glyphs) loaded: {ms:.0} ms → {}", face.mapped_chars().len(), r["texts"]); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + +#[test] +fn a_compound_with_a_locked_or_hidden_part_stays_whole() { + let mut s = session(); + // "B" outlines as a compound path of three contours. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let b = children_of(&s, g)[1]; + let part = children_of(&s, b)[1]; + s.edit("test", |d, _| { + d.node_mut(NodeId(part)).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A"]), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(part)).unwrap().locked, "B's locked part, and B, stay as they are"); +} + +#[test] +fn a_group_with_an_attributes_note_keeps_its_type_inside() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + s.execute("attributes.set", &json!({"ids": [g], "note": "logo, keep"})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let id = r["ids"][0].as_u64().unwrap(); + assert_eq!(children_of(&s, g), vec![id], "the group and its note stay, holding the type"); +} + +#[test] +fn nothing_retypable_reads_no_font() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default()); + d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("(1 checked)"), "the masked shape is reported, and no font was indexed: {e}"); +} + +#[test] +fn tracked_one_contour_letters_still_become_type() { + for text in ["LIT", "HELLO", "LIST"] { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30})).unwrap()["id"].as_u64().unwrap(); + let n = text.len() as u64; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": n, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}"); + assert!(texts.len() > 1, "the tracking splits the line: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + +/// How long Retype takes on a few hundred CJK outlines at once (run with `--ignored --nocapture`; +/// skips when no large CJK font is installed). Not a pass/fail budget: it prints. +#[test] +#[ignore = "timing: needs an installed CJK font"] +fn timing_with_hundreds_of_cjk_outlines() { + let db = vectorcraft_text::FontDb::global(); + let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f)) + else { + eprintln!("skipped: no large CJK font installed"); + return; + }; + let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap(); + // 300 common ideographs, ten lines of thirty. + let chars: Vec = (0x4E00u32..).filter_map(char::from_u32).filter(|c| face.covers(*c)).take(300).collect(); + let mut s = session(); + let mut groups = vec![]; + for (i, line) in chars.chunks(30).enumerate() { + let text: String = line.iter().collect(); + groups.push(outlined(&mut s, json!({"x": 20, "y": 40 + 30 * i, "text": text, "size": 20, "font": family, "style": face.style}))); + } + for run in ["cold", "warm"] { + s.execute("select.set", &json!({"ids": groups})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap(); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + let typed: usize = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().chars().count()).sum(); + eprintln!( + "{run}: Retype of {} {family} outlines: {ms:.0} ms → {typed} characters typed, {} unmatched", + chars.len(), + r["unmatched"].as_array().unwrap().len() + ); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + +#[test] +fn a_long_tracked_line_is_checked_in_time() { + // Tracking splits the line at every glyph: the layout check must not lay out the rest of the + // line again after each split. + let text = "abe".repeat(150); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), text); + assert_eq!(r["unmatched"], json!([])); + eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len()); +} diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 2b746b7634..b93c378fea 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1279,40 +1279,63 @@ impl GroupEdit { /// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their /// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors -/// are added as new swatches and swatches past the end are removed. Paints linked to its global +/// are added as new swatches and swatches past the end are removed. With `colors_only`, a swatch +/// that is not a color (a gradient, pattern or None swatch) keeps its place and paint and takes no +/// entry of `colors`, which go to the group's color swatches in order. Paints linked to its global /// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch /// (None, Registration) it would change or remove is refused. -pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option], rename: Option<&str>, cmd: &str) -> Result { +pub(super) fn rewrite_group( + d: &mut Document, + group: &str, + colors: &[Option], + colors_only: bool, + rename: Option<&str>, + cmd: &str, +) -> Result { let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?; let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) { Some(n) => d.free_swatch_name(n), None => group.to_string(), }; let old = &d.swatch_groups[gi].swatches; + // The place in `colors` of each swatch's new color; none for a swatch kept as it is. + let mut taken = 0; + let places: Vec> = old + .iter() + .map(|w| { + (!colors_only || w.paint.color().is_some()).then(|| { + taken += 1; + taken - 1 + }) + }) + .collect(); + let new_color = |place: Option| place.and_then(|i| colors.get(i).copied().flatten()); if let Some(w) = old .iter() - .enumerate() - .find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c))) - .map(|x| x.1) + .zip(&places) + .find(|(w, place)| place.is_some() && w.is_reserved() && new_color(**place).is_none_or(|c| w.paint.color() != Some(c))) + .map(|x| x.0) { return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name))); } let colorized_ok = super::paint::check_colorized(d).is_ok(); let mut relinks = vec![]; let old = std::mem::take(&mut d.swatch_groups[gi].swatches); - let old_len = old.len(); - // The swatches that stay, each with its new color. - let mut kept: Vec<(Swatch, Color)> = vec![]; - for (i, w) in old.into_iter().enumerate() { - match colors.get(i).copied().flatten() { - Some(c) => kept.push((w, c)), - None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }), - None => {} + // The swatches that stay, each with its new color (none for one kept as it is). + let mut kept: Vec<(Swatch, Option)> = vec![]; + for (w, place) in old.into_iter().zip(places) { + match (place, new_color(place)) { + (None, _) => kept.push((w, None)), + (_, Some(c)) => kept.push((w, Some(c))), + (_, None) if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }), + (_, None) => {} } } let mut swatches = Vec::with_capacity(kept.len()); for (mut w, c) in kept { - if w.paint.color() != Some(c) { + if let Some(c) = c + && w.paint.color() != Some(c) + { // A tint swatch becomes a colour of its own. w.paint = Paint::solid(c); if w.global { @@ -1325,7 +1348,7 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option Result { { return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::>(), "relinked": 0})); } - let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?; + let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, false, rename, C))?; e.defaults(s)?; Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked})) } diff --git a/crates/engine/src/cmd/toast.rs b/crates/engine/src/cmd/toast.rs new file mode 100644 index 0000000000..e2eb41bd21 --- /dev/null +++ b/crates/engine/src/cmd/toast.rs @@ -0,0 +1,283 @@ +//! `app.toast`: a short message shown over the window that does not stop work and goes away by +//! itself (a toast). Scripts (`vc.run`), actions (a recorded step), MCP clients and plug-ins raise +//! one with the command, and the app's code can raise one with [`Session::toast`]. The engine +//! queues the messages and the desktop app takes them each frame ([`Session::take_toasts`]) and +//! shows them. A failed script run puts the documents back but keeps the messages it raised. + +use std::collections::VecDeque; + +use serde_json::{Value, json}; + +use super::{CommandSpec, Result, always, bad, cmd}; +use crate::Session; + +const ID: &str = "app.toast"; + +/// The most characters a message has. +pub const MAX_CHARS: usize = 500; + +/// How long a message shows when `seconds` is omitted, and the shortest and longest time it may +/// show. +pub const DEFAULT_SECONDS: f64 = 4.0; +pub const MIN_SECONDS: f64 = 0.5; +pub const MAX_SECONDS: f64 = 60.0; + +/// The most messages waiting for the app to take them: past it the oldest one goes. A session +/// without a window (the headless MCP server, `vectorcraft-cli run`) never takes them. +pub const MAX_QUEUED: usize = 32; + +/// What kind of news a message is, which sets its color. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Level { + #[default] + Info, + Success, + Warning, + Error, +} + +impl Level { + pub const ALL: [Level; 4] = [Level::Info, Level::Success, Level::Warning, Level::Error]; + + /// Its `level` value. + pub fn param(self) -> &'static str { + match self { + Level::Info => "info", + Level::Success => "success", + Level::Warning => "warning", + Level::Error => "error", + } + } + + /// The level whose `level` value is `param`. + pub fn from_param(param: &str) -> Option { + Level::ALL.into_iter().find(|l| l.param() == param) + } +} + +/// A message to show. +#[derive(Clone, Debug, PartialEq)] +pub struct Toast { + pub message: String, + pub level: Level, + /// How long it shows, in seconds. + pub seconds: f64, +} + +impl Toast { + /// A message of `level` shown for [`DEFAULT_SECONDS`]. + pub fn new(message: impl Into, level: Level) -> Toast { + Toast { message: message.into(), level, seconds: DEFAULT_SECONDS } + } +} + +/// The messages waiting for the app to show them. +#[derive(Clone, Debug, Default)] +pub struct Queue(VecDeque); + +impl Session { + /// Queue `toast` for the app to show. With [`MAX_QUEUED`] waiting, the oldest one goes. Its + /// time is held to [`MIN_SECONDS`] to [`MAX_SECONDS`], and a time that is not a number is + /// [`DEFAULT_SECONDS`]. + pub fn toast(&mut self, mut toast: Toast) { + toast.seconds = if toast.seconds.is_nan() { DEFAULT_SECONDS } else { toast.seconds.clamp(MIN_SECONDS, MAX_SECONDS) }; + while self.toasts.0.len() >= MAX_QUEUED { + self.toasts.0.pop_front(); + } + self.toasts.0.push_back(toast); + } + + /// Take the messages queued since the last call, oldest first. + pub fn take_toasts(&mut self) -> Vec { + self.toasts.0.drain(..).collect() + } +} + +pub fn specs() -> Vec { + vec![cmd!( + "app.toast", + "Show Message", + [], + None, + "{message: string (1 to 500 characters, not only whitespace), level?: \"info\" | \"success\" | \"warning\" | \"error\" (default \"info\"), seconds?: number 0.5 to 60 (default 4)} show `message` over the window without stopping work: it goes away after `seconds` or when clicked; messages stack at the window's bottom right, the newest lowest, at most 5 at once; edits no document; an action records it as a step → {message, level, seconds}", + always, + run + )] +} + +fn run(s: &mut Session, p: &Value) -> Result { + let toast = parse(p)?; + let r = json!({"message": &toast.message, "level": toast.level.param(), "seconds": toast.seconds}); + s.toast(toast); + Ok(r) +} + +/// The message `p` asks for; an invalid value of any key is an error. +fn parse(p: &Value) -> Result { + let message = match p.get("message") { + Some(Value::String(m)) => m, + Some(_) => return Err(bad(ID, "`message` must be a string")), + None => return Err(bad(ID, "`message` is required")), + }; + if message.trim().is_empty() { + return Err(bad(ID, "`message` must have a character other than whitespace")); + } + let chars = message.chars().count(); + if chars > MAX_CHARS { + return Err(bad(ID, format!("`message` has {chars} characters; at most {MAX_CHARS} are allowed"))); + } + let level = match p.get("level") { + None => Level::default(), + Some(v) => v.as_str().and_then(Level::from_param).ok_or_else(|| { + let all: Vec<&str> = Level::ALL.iter().map(|l| l.param()).collect(); + bad(ID, format!("`level` must be one of {}", all.join(", "))) + })?, + }; + let seconds = match p.get("seconds") { + None => DEFAULT_SECONDS, + Some(v) => v + .as_f64() + .filter(|s| (MIN_SECONDS..=MAX_SECONDS).contains(s)) + .ok_or_else(|| bad(ID, format!("`seconds` must be a number from {MIN_SECONDS} to {MAX_SECONDS}")))?, + }; + Ok(Toast { message: message.clone(), level, seconds }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_message_is_queued_with_its_defaults() { + let mut s = Session::new(); + let r = s.execute(ID, &json!({"message": "Saved 3 files"})).unwrap(); + assert_eq!(r, json!({"message": "Saved 3 files", "level": "info", "seconds": 4.0})); + assert_eq!(s.take_toasts(), vec![Toast::new("Saved 3 files", Level::Info)]); + // Taken once. + assert_eq!(s.take_toasts(), vec![]); + } + + #[test] + fn level_and_seconds_are_kept() { + let mut s = Session::new(); + for level in Level::ALL { + s.execute(ID, &json!({"message": "m", "level": level.param(), "seconds": 0.5})).unwrap(); + } + s.execute(ID, &json!({"message": "long", "seconds": 60})).unwrap(); + let got: Vec<(Level, f64)> = s.take_toasts().iter().map(|t| (t.level, t.seconds)).collect(); + assert_eq!(got, vec![(Level::Info, 0.5), (Level::Success, 0.5), (Level::Warning, 0.5), (Level::Error, 0.5), (Level::Info, 60.0)]); + } + + #[test] + fn invalid_values_are_errors_and_queue_nothing() { + let mut s = Session::new(); + let long = "x".repeat(MAX_CHARS + 1); + for p in [ + json!({}), + json!({"message": 3}), + json!({"message": ""}), + json!({"message": " \n\t"}), + json!({"message": long}), + json!({"message": "m", "level": "loud"}), + json!({"message": "m", "level": 1}), + json!({"message": "m", "seconds": 0.4}), + json!({"message": "m", "seconds": 61}), + json!({"message": "m", "seconds": "4"}), + json!({"message": "m", "seconds": null}), + ] { + let e = s.execute(ID, &p).unwrap_err().to_string(); + assert!(e.contains(ID), "{p}: {e}"); + } + assert_eq!(s.take_toasts(), vec![]); + // The longest message is allowed, counted in characters, not bytes. + let most = "é".repeat(MAX_CHARS); + s.execute(ID, &json!({"message": most})).unwrap(); + assert_eq!(s.take_toasts().len(), 1); + } + + #[test] + fn a_message_queued_by_the_app_shows_for_0_5_to_60_seconds() { + let mut s = Session::new(); + for seconds in [f64::INFINITY, 1e9, f64::NEG_INFINITY, 0.0, f64::NAN, 10.0] { + s.toast(Toast { seconds, ..Toast::new("m", Level::Info) }); + } + let got: Vec = s.take_toasts().iter().map(|t| t.seconds).collect(); + assert_eq!(got, vec![MAX_SECONDS, MAX_SECONDS, MIN_SECONDS, MIN_SECONDS, DEFAULT_SECONDS, 10.0]); + } + + #[test] + fn the_oldest_waiting_message_goes_past_the_limit() { + let mut s = Session::new(); + for i in 0..MAX_QUEUED + 2 { + s.toast(Toast::new(format!("{i}"), Level::Info)); + } + let left: Vec = s.take_toasts().into_iter().map(|t| t.message).collect(); + assert_eq!(left.len(), MAX_QUEUED); + assert_eq!(left.first().map(String::as_str), Some("2")); + assert_eq!(left.last().map(String::as_str), Some("33")); + } + + #[test] + fn a_message_is_journaled_without_an_undo_step_or_a_document() { + let mut s = Session::new(); + // No document open. + s.execute(ID, &json!({"message": "no document"})).unwrap(); + assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "no document"}))); + s.execute("file.new", &json!({})).unwrap(); + let undo = s.active().unwrap().history.undo.len(); + let revision = s.active().unwrap().revision; + s.execute(ID, &json!({"message": "m", "level": "success"})).unwrap(); + assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "m", "level": "success"}))); + assert_eq!(s.active().unwrap().history.undo.len(), undo); + assert_eq!(s.active().unwrap().revision, revision); + } + + #[test] + fn a_script_raises_a_message_with_vc_run() { + let mut s = Session::new(); + let r = s + .execute( + "script.run", + &json!({"source": "vc.run('app.toast', {message: 'Done: ' + (1 + 1), level: 'success'});", "name": "t.js", "answers": []}), + ) + .unwrap(); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + assert_eq!(s.take_toasts(), vec![Toast::new("Done: 2", Level::Success)]); + } + + #[test] + fn a_failed_script_run_puts_the_documents_back_and_keeps_its_messages() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let art = format!("{:?}", s.active().unwrap().doc.layers); + let e = s + .execute( + "script.run", + &json!({ + "source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.run('app.toast', {message: 'Failed: no artboard'}); throw new Error('stop');", + "name": "t.js", + "answers": [], + }), + ) + .unwrap_err() + .to_string(); + assert!(e.contains("stop"), "{e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art, "the rectangle is put back"); + assert_eq!(s.take_toasts(), vec![Toast::new("Failed: no artboard", Level::Info)]); + } + + #[test] + fn a_command_batch_raises_its_messages_in_order() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute( + "command.batch", + &json!({"commands": [ + {"command": "app.toast", "params": {"message": "one"}}, + {"command": "app.toast", "params": {"message": "two", "level": "warning"}}, + ]}), + ) + .unwrap(); + assert_eq!(s.take_toasts(), vec![Toast::new("one", Level::Info), Toast::new("two", Level::Warning)]); + } +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 359b369a89..f9c6471812 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -10,8 +10,8 @@ use super::object::choice; use super::threads::ThreadIndex; use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds}; use super::{ - CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids, - number_or, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, index_opt, + named_ids, number_or, object_param, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Find and Replace…", ["Edit"], None, - "{find, replace?: \"\", matchCase?: false, wholeWord?: false, ids?} replace in every text object (or ids) → {count}. Matches never span style runs.", + "{find, replace?: \"\", matchCase?: false, wholeWord?: false, hiddenLayers?: false, lockedLayers?: false, ids?} replace every match in the type the search reaches (or in ids, whatever their layers), as one undo step → {count (every match), replaced (the matches that did not already read as `replace`)}. The search reaches visible, unlocked type on visible, unlocked layers, off locked artboards; hiddenLayers adds the type of hidden layers and sublayers and lockedLayers that of locked ones, while a hidden or locked object or group keeps its type out. Matches never span style runs. When nothing matches, or every match already reads as `replace`, nothing changes and no undo step is recorded.", has_doc, find_replace ), @@ -129,10 +129,19 @@ pub fn specs() -> Vec { "Find Next", ["Edit"], None, - "{find, matchCase?, wholeWord?} select the next text object (after the selected one, wrapping) containing `find` → {id|null}", + "{find, matchCase?: false, wholeWord?: false, backwards?: false, hiddenLayers?: false, lockedLayers?: false, from?: {id, start, end} (a match this command returned, or the range edit.replaceMatch returned)} find the next match of `find` in the type edit.findReplace reaches and select its type object → {id, start, end (the match's bytes in the object's plain text), index (its place among all the matches, from 1), count, selected} or {id: null, count: 0}. The search visits type objects from the top of the stacking order down and each object's matches in reading order; backwards visits the objects from the bottom up and each object's matches from the last. It goes on after `from` and, past the last match, starts again at the first. Without `from` it goes on after the first selected type object, and with no type selected, or with a null `from`, it starts at the first match. A match on a hidden or locked layer is returned with selected false and the selection stays as it is. Nothing is recorded for undo.", has_doc, find_next ), + cmd!( + "edit.replaceMatch", + "Replace", + [], + None, + "{find, replace?: \"\", matchCase?: false, wholeWord?: false, id, start, end} replace one match of `find`, the bytes start..end of type object id as edit.findNext returns them, with `replace`, as one undo step → {id, start, end (the replacement's bytes; pass them to edit.findNext as `from` to go on), replaced}. Bytes that are no match of `find` are refused. When the match already reads as `replace`, nothing changes, no undo step is recorded and replaced is false.", + has_doc, + replace_one + ), cmd!( "edit.pasteWithoutFormatting", "Paste without Formatting", @@ -1657,14 +1666,9 @@ fn is_word(c: char) -> bool { c.is_alphanumeric() || c == '_' } -/// Byte ranges of `needle` in `hay`. -pub(crate) fn find_all(hay: &str, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> { - find_all_between(hay, needle, match_case, whole_word, None, None) -} - -/// [`find_all`] in run `i` of `runs`: a whole word looks past the run's ends at the characters -/// next to it, so a change of style inside a word is not a word boundary (#5901). Matches stay -/// inside the run. +/// Byte ranges of `needle` in run `i` of `runs`: a whole word looks past the run's ends at the +/// characters next to it, so a change of style inside a word is not a word boundary (#5901). +/// Matches stay inside the run. fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> { let Some(run) = runs.get(i) else { return vec![] }; let before = runs.get(..i).and_then(|r| r.iter().rev().find_map(|r| r.text.chars().next_back())); @@ -1672,8 +1676,8 @@ fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole find_all_between(&run.text, needle, match_case, whole_word, before, after) } -/// [`find_all`], with `before` and `after` the characters on either side of `hay` (none at the -/// text's ends), which a whole word must not touch either. +/// Byte ranges of `needle` in `hay`, with `before` and `after` the characters on either side of +/// `hay` (none at the text's ends), which a whole word must not touch either. fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, before: Option, after: Option) -> Vec<(usize, usize)> { let nc: Vec = needle.chars().collect(); if nc.is_empty() { @@ -1705,102 +1709,234 @@ fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, /// The visible, unlocked type objects of visible, unlocked layers, off locked artboards, in paint /// order: the text Find and Replace and Check Spelling go through. pub(crate) fn all_texts(d: &Document) -> Vec { - fn visit(n: &Node, locks: &LockedArtboards<'_>, v: &mut Vec) { - if !n.visible || n.locked { + searched_texts(d, false, false) +} + +/// [`all_texts`], with the type of hidden layers (`hidden_layers`) and of locked layers +/// (`locked_layers`) as well, as Check Hidden Layers and Check Locked Layers of Find and Replace +/// ask. The switches are about layers and sublayers: a hidden or locked object or group keeps its +/// type out, and so does a locked artboard. +fn searched_texts(d: &Document, hidden_layers: bool, locked_layers: bool) -> Vec { + fn visit(n: &Node, locks: &LockedArtboards<'_>, layers: (bool, bool), v: &mut Vec) { + let layer = matches!(n.kind, NodeKind::Layer { .. }); + if (!n.visible && !(layer && layers.0)) || (n.locked && !(layer && layers.1)) { return; } if matches!(n.kind, NodeKind::Text(_)) && !locks.holds_id(n.id) { v.push(n.id); } for c in n.children().into_iter().flatten() { - visit(c, locks, v); + visit(c, locks, layers, v); } } let mut v = vec![]; let locks = d.locked_artboards(); for l in &d.layers { - visit(l, &locks, &mut v); + visit(l, &locks, (hidden_layers, locked_layers), &mut v); } v } +/// What Find and Replace looks for: the text, Match Case and Find Whole Word. +struct Query { + find: String, + match_case: bool, + whole_word: bool, +} + +impl Query { + /// The `find`, `matchCase` and `wholeWord` params of command `c`. An empty or missing `find` + /// is an error. + fn of(p: &Value, c: &str) -> Result { + let find = text_param(p, "find", c)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(c, "missing `find`"))?.to_string(); + Ok(Self { find, match_case: switch_or(p, "matchCase", false, c)?, whole_word: switch_or(p, "wholeWord", false, c)? }) + } + + /// The matches in `t`, in reading order, each as (run, start, end) with `start..end` the bytes + /// of the match in the object's plain text. A match stays inside one style run, and an inline + /// graphic is art, not characters to find. + fn matches(&self, t: &TextObject) -> Vec<(usize, usize, usize)> { + let mut hits = vec![]; + let mut base = 0; + for (ri, r) in t.runs.iter().enumerate() { + if r.inline.is_none() { + hits.extend( + find_in_run(&t.runs, ri, &self.find, self.match_case, self.whole_word).into_iter().map(|(a, b)| (ri, base + a, base + b)), + ); + } + base += r.text.len(); + } + hits + } +} + +/// Replace bytes `start..end` of the plain text of `t`, which lie inside run `run`, with `rep`. +/// The paragraph styles and the ruby follow the edit, as `text.editRange` moves them. The caller +/// refreshes the bounds. +fn replace_match(t: &mut TextObject, run: usize, start: usize, end: usize, rep: &str) { + let base: usize = t.runs.iter().take(run).map(|r| r.text.len()).sum(); + let (Some(a), Some(b)) = (start.checked_sub(base), end.checked_sub(base)) else { return }; + if !t.runs.get(run).is_some_and(|r| a <= b && r.text.is_char_boundary(a) && r.text.is_char_boundary(b)) { + return; + } + t.splice_paras(start, end, rep); + if let Some(r) = t.runs.get_mut(run) { + r.text.replace_range(a..b, rep); + } + t.ruby_after_replace(start, end, rep.len()); +} + fn find_replace(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.findReplace"; - let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string(); + let q = Query::of(p, C)?; let rep = text_param(p, "replace", C)?.unwrap_or("").to_string(); - let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?); + let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?); let ids = match p.get("ids").filter(|v| !v.is_null()) { Some(_) => text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?), - None => all_texts(&s.doc()?.doc), + None => searched_texts(&s.doc()?.doc, hidden, locked), }; let st = s.doc()?; - let total: usize = ids + // Every match, and the matches that do not already read as the replacement. + let (total, replaced) = ids .iter() .filter_map(|id| match &st.doc.node(*id)?.kind { - NodeKind::Text(t) => Some((0..t.runs.len()).map(|i| find_in_run(&t.runs, i, &find, mc, ww).len()).sum::()), + NodeKind::Text(t) => { + let plain = t.plain_text(); + let hits = q.matches(t); + Some((hits.len(), hits.iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).count())) + } _ => None, }) - .sum(); - if total == 0 { - return Ok(json!({ "count": 0 })); + .fold((0, 0), |(n, r), (hn, hr)| (n + hn, r + hr)); + if replaced == 0 { + return Ok(json!({ "count": total, "replaced": 0 })); } super::overprint::edit_counted(s, "Replace", |d| { let mut changed = 0; for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; - // Matches as (run, start, end) with offsets inside the run. Inline graphics are art, not - // characters to rewrite. - let mut hits = vec![]; - let mut base = 0; - for (ri, r) in t.runs.iter().enumerate() { - if r.inline.is_none() { - for (a, b) in find_in_run(&t.runs, ri, &find, mc, ww) { - if r.text.get(a..b) != Some(rep.as_str()) { - hits.push((ri, base + a, base + b, a, b)); - } - } - } - base += r.text.len(); - } + let plain = t.plain_text(); + let hits: Vec<_> = q.matches(t).into_iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).collect(); if hits.is_empty() { continue; } - // Last match first, so the offsets of earlier ones stay valid. The paragraph styles follow - // each edit, as `text.editRange` does. - for (ri, ta, tb, a, b) in hits.into_iter().rev() { - t.splice_paras(ta, tb, &rep); - if let Some(r) = t.runs.get_mut(ri) { - r.text.replace_range(a..b, &rep); - } + // Last match first, so the offsets of earlier ones stay valid. + for (ri, a, b) in hits.into_iter().rev() { + replace_match(t, ri, a, b, &rep); } changed += 1; refresh_bounds(t); } Ok(changed) })?; - Ok(json!({ "count": total })) + Ok(json!({ "count": total, "replaced": replaced })) +} + +/// A match of Find and Replace: bytes `start..end` of the plain text of type object `id`. +#[derive(Clone, Copy)] +struct Match { + id: NodeId, + start: usize, + end: usize, +} + +impl Match { + /// The `id`, `start` and `end` that `p` gives for a match, under command `c`: an object id and + /// two byte offsets, put in order as `text.editRange` orders its own. + fn of(p: &Value, c: &str) -> Result { + let whole = |key: &str| index_opt(p, key, c)?.ok_or_else(|| bad(c, format!("missing `{key}`"))); + let id = object_param(p, "id", c)?.ok_or_else(|| bad(c, "missing `id`"))?; + let (start, end) = (whole("start")?, whole("end")?); + Ok(Self { id, start: start.min(end), end: start.max(end) }) + } } fn find_next(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.findNext"; - let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string(); - let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?); + let q = Query::of(p, C)?; + let backwards = switch_or(p, "backwards", false, C)?; + let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?); + // A `from` that is no object gives no `id`, and is refused as one without it. A null `from` + // starts at the first match, whatever is selected. + let from = match p.get("from") { + None => None, + Some(Value::Null) => Some(None), + Some(v) => Some(Some(Match::of(v, C)?)), + }; let st = s.doc()?; - let all = all_texts(&st.doc); - let cur = st.selection.objects.first().and_then(|id| all.iter().position(|x| x == id)); - let n = all.len(); - let start = cur.map(|c| c + 1).unwrap_or(0); - let hit = (0..n).map(|k| all[(start + k) % n.max(1)]).find(|id| match st.doc.node(*id).map(|n| &n.kind) { - Some(NodeKind::Text(t)) => !find_all(&t.plain_text(), &find, mc, ww).is_empty(), - _ => false, - }); - match hit { - Some(id) => { - s.select(|_, sel| sel.set([id]))?; - Ok(json!({ "id": id.0 })) - } - None => Ok(json!({ "id": null })), + // The objects in the order the search visits them: from the top of the stacking order down, + // or with Search Backwards from the bottom up. + let mut order = searched_texts(&st.doc, hidden, locked); + if !backwards { + order.reverse(); } + // Every match in that order as (object's place, match): inside an object in reading order, or + // with Search Backwards from its end. + let mut all: Vec<(usize, Match)> = vec![]; + for (place, id) in order.iter().enumerate() { + let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + let mut hits = q.matches(t); + if backwards { + hits.reverse(); + } + all.extend(hits.into_iter().map(|(_, start, end)| (place, Match { id: *id, start, end }))); + } + if all.is_empty() { + return Ok(json!({ "id": null, "count": 0 })); + } + // The search goes on from `from`, or from the whole of the first selected type object it + // visits, so that the same call again reaches the next object. From anywhere else it starts + // at the first match. + let from = from.unwrap_or_else(|| { + st.selection.objects.iter().filter(|id| order.contains(id)).find_map(|id| match &st.doc.node(*id)?.kind { + NodeKind::Text(t) => Some(Match { id: *id, start: 0, end: t.runs.iter().map(|r| r.text.len()).sum() }), + _ => None, + }) + }); + let after = |(place, m): &(usize, Match), at: usize, f: &Match| { + *place > at || (*place == at && if backwards { m.end <= f.start } else { m.start >= f.end }) + }; + let k = from + .and_then(|f| order.iter().position(|id| *id == f.id).map(|at| (at, f))) + .and_then(|(at, f)| all.iter().position(|hit| after(hit, at, &f))) + .unwrap_or(0); + let Some((_, m)) = all.get(k).copied() else { return Ok(json!({ "id": null, "count": 0 })) }; + let count = all.len(); + // Type that a selection tool can't reach (on a hidden or locked layer) is found without being + // selected. + let selected = all_texts(&st.doc).contains(&m.id); + if selected && st.selection.objects != [m.id] { + s.select(|_, sel| sel.set([m.id]))?; + } + let index = if backwards { count - k } else { k + 1 }; + Ok(json!({ "id": m.id.0, "start": m.start, "end": m.end, "index": index, "count": count, "selected": selected })) +} + +fn replace_one(s: &mut Session, p: &Value) -> Result { + const C: &str = "edit.replaceMatch"; + let q = Query::of(p, C)?; + let rep = text_param(p, "replace", C)?.unwrap_or("").to_string(); + let m = Match::of(p, C)?; + let st = s.doc()?; + let t = match st.doc.node(m.id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t, + Some(_) => return Err(bad(C, format!("node {} is not text", m.id.0))), + None => return Err(EngineError::NoNode(m.id)), + }; + let Some((run, ..)) = q.matches(t).into_iter().find(|(_, a, b)| (*a, *b) == (m.start, m.end)) else { + return Err(bad(C, format!("no match of `find` at bytes {}..{} of object {}", m.start, m.end, m.id.0))); + }; + let end = m.start + rep.len(); + if t.plain_text().get(m.start..m.end) == Some(rep.as_str()) { + return Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": false })); + } + s.edit("Replace", |d, _| { + let Some(NodeKind::Text(t)) = d.node_mut(m.id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(m.id)) }; + replace_match(t, run, m.start, m.end, &rep); + refresh_bounds(t); + Ok(()) + })?; + Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": true })) } // ---------- Paste without Formatting ---------- diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index 8886c597da..f68551aefe 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -250,7 +250,6 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result { craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")), _ => bad(cmd, format!("the variable library is not well-formed XML: {e}")), })?; - crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?; let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else { return Err(bad(cmd, "the file holds no `variableSets` element")); }; diff --git a/crates/engine/src/cmd/xmlattrs.rs b/crates/engine/src/cmd/xmlattrs.rs deleted file mode 100644 index 6dd2578fae..0000000000 --- a/crates/engine/src/cmd/xmlattrs.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode. -//! -//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the -//! shared strict reader and remove this second event pass when that dependency is updated. - -/// Check names before canonical/local-name rewriting can collapse distinct attributes. -/// The event reader and namespace scope use the same caller-supplied resource caps. -pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> { - use std::collections::BTreeSet; - - let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict(); - let mut events = opts.events(xml); - let mut bindings: Vec<(String, String)> = Vec::new(); - let mut scopes = Vec::new(); - while let Some(event) = events.next().map_err(|e| e.to_string())? { - match event { - craft_xml::Event::Start { attrs, .. } => { - scopes.push(bindings.len()); - let mut raw = BTreeSet::new(); - for (key, value) in &attrs { - if !raw.insert(key.as_str()) { - return Err(format!("duplicate attribute `{key}`")); - } - if let Some(prefix) = key.strip_prefix("xmlns:") { - if bindings.len() >= limits.max_attrs { - return Err("too many in-scope namespace declarations".into()); - } - bindings.push((prefix.to_string(), value.clone())); - } - } - let mut expanded = BTreeSet::new(); - for (key, _) in &attrs { - if key == "xmlns" || key.starts_with("xmlns:") { - continue; - } - // Default namespaces do not apply to attributes. Preserve undeclared - // prefixes for standalone SVG library fragments, as the importer did. - let name = match key.split_once(':') { - Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local), - Some((prefix, local)) => { - bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local)) - } - None => ("", key.as_str()), - }; - if !expanded.insert(name) { - return Err(format!("duplicate expanded attribute `{key}`")); - } - } - } - craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)), - _ => {} - } - } - Ok(()) -} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index de780f406c..94ea383690 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,7 @@ use vectorcraft_tools::{PaintDefaults, Tool}; pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; +pub use cmd::flare::flare_settings; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; @@ -198,7 +199,8 @@ pub struct Session { /// `plugin.install` takes `grant` and `allowHeavy` from any request /// ([`Session::allow_plugin_grants_from_requests`]). plugin_grants_from_requests: bool, - /// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved. + /// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first, at most + /// [`cmd::RECENT_URLS`]; not saved. pub recent_urls: Vec, /// The saved tracing presets' revision and latest changes ([`Session::trace_presets_revision`]). pub(crate) trace_preset_changes: cmd::TracePresetChanges, @@ -360,6 +362,8 @@ pub struct Session { /// Set while [`Session::tool_typed_text`] passes keyboard input to the active tool /// ([`vectorcraft_tools::ToolContext::typed_from_keyboard`]). keyboard_text: bool, + /// The messages `app.toast` and [`Session::toast`] queued for the app to show; not saved. + pub(crate) toasts: cmd::toast::Queue, } impl Default for Session { @@ -415,7 +419,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::PreviewCopies; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; -pub use prefs::{DrawMode, PluginBudget, Prefs}; +pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs}; pub use sanity::TOO_DEEP; pub(crate) use sanity::{deselect_hidden, is_guide_path}; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 6d044eace3..d2e615992a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -97,6 +97,13 @@ pub struct Prefs { /// A single-key tool shortcut held down chooses its tool until the key is let go, and then the /// tool active before comes back; a quick press chooses the tool for good. pub hold_tool_keys: bool, + /// Hold shortcuts act (Edit › Keyboard Shortcuts › Hold Shortcuts, off by default): a key with a + /// hold shortcut runs it when held for [`Self::key_hold_delay`], and its own shortcut when let go + /// sooner. Off, every key runs on its press and the dialog shows no Hold column. + pub hold_shortcuts: bool, + /// Seconds a key with a hold shortcut must stay down before the hold shortcut runs (Hold + /// Shortcut Delay, 0.2 to 1.0). VectorCraft's own default, 0.35. + pub key_hold_delay: f64, /// With View › Show Bounding Box on, the bounding box stays visible while a drag moves the /// selection, and the shape tools that show it draw it around the shape being drawn. Off (the /// default), it hides during a move and while a shape is drawn, except that a Selection tool @@ -420,6 +427,21 @@ pub struct Prefs { pub import_matches: Vec, } +/// The default Hold Shortcut Delay, in seconds (VectorCraft's own value). +pub const KEY_HOLD_DELAY: f64 = 0.35; +/// The range of the Hold Shortcut Delay, in seconds. +pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0); + +impl Prefs { + /// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not + /// checked against the range, so a value outside it is brought inside, and one that is not a + /// number gives the default. + pub fn key_hold_delay(&self) -> f64 { + let (min, max) = KEY_HOLD_DELAY_RANGE; + if self.key_hold_delay.is_finite() { self.key_hold_delay.clamp(min, max) } else { KEY_HOLD_DELAY } + } +} + impl Default for Prefs { fn default() -> Self { let s = |v: &str| v.to_string(); @@ -451,6 +473,8 @@ impl Default for Prefs { scrub_numeric_fields: true, trackpad_rotate_view: true, hold_tool_keys: true, + hold_shortcuts: false, + key_hold_delay: KEY_HOLD_DELAY, bounding_box_while_moving_and_drawing: false, paste_offset: 10.0, selection_tolerance: 3.0, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0dd9a46b6b..d811da6e2e 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1559,12 +1559,14 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { } } -/// `message`, with what to do about a failure that comes from a script written for another program. -fn explained(kind: &RunErrorKind, message: &str) -> String { +/// `e`'s message, with what to do about a failure that comes from a script written for another +/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. +fn explained(e: &RunError) -> String { const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"]; + let message = &e.message; let names_host_object = message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); - if *kind == RunErrorKind::Thrown && names_host_object { + if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") } else { message.to_string() @@ -1582,7 +1584,7 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { include::FailKind::Limit => (RunErrorKind::Limit(LimitKind::Host), f.message), }; let file = (f.index > 0).then_some(f.file); - (RunError { kind, message, line: f.line, column: f.column }, file) + (RunError { kind, message, line: f.line, column: f.column, authored: false }, file) } /// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, @@ -1591,20 +1593,20 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option { let (e, index, file) = map(&host.script_map.borrow()); @@ -1777,6 +1779,15 @@ impl Session { self.script_report.as_ref().filter(|r| r["ok"] == false).map(failure_text) } + /// [`Self::script_failure_text`] split around the message when that message is text the script + /// supplied itself (`messageOrigin` `script`): the text before it, the message and the text after + /// it. `None` when the last run did not fail, or failed with one of the app's own errors. + pub fn script_authored_failure(&self) -> Option<(String, &str, String)> { + let r = self.script_report.as_ref().filter(|r| r["ok"] == false && r["messageOrigin"] == "script")?; + let (before, after) = failure_frame(r); + Some((before, r["message"].as_str().unwrap_or_default(), after)) + } + /// Has the running script used up its growth allowance, so a person must answer? A run asked /// to stop no longer waits: the next [`Session::script_pump`] ends it. pub fn script_waiting(&self) -> bool { @@ -1873,7 +1884,7 @@ impl Session { }; drop(key); let kind = LimitKind::Interrupted; - let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; let _ = self.script_failed(job, &e); true } @@ -2120,14 +2131,14 @@ impl Session { // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. if job.realm.waits() { let kind = LimitKind::Interrupted; - let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; return Some(self.script_failed(job, &e)); } job.host.calls_this_slice.set(0); let outcome = run_slice(self, &mut job); match outcome { Err(panic) => { - let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false }; Some(self.script_failed(job, &e)) } Ok(Err(e)) => Some(self.script_failed(job, &e)), @@ -2144,7 +2155,7 @@ impl Session { } else { format!("`answers` has {n} answers the script did not use") }; - Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 })) + Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false })) } Ok(Ok(Progress::Done(_))) => { let r = self.script_commit(job); @@ -2179,7 +2190,7 @@ impl Session { let unwritten = job.host.flush_files(); if !unwritten.is_empty() { let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", ")); - let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0, authored: false }; return self.script_failed(job, &e); } // The working copy goes into the session; `job.world` holds the state before the run. @@ -2197,7 +2208,7 @@ impl Session { if changed && (!crate::sanity::doc_sane(&st.doc, &st.selection) || st.doc.too_deep(None)) { job.world.docs = start; job.world.swap(self); - let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0, authored: false }; return self.script_failed(job, &e); } } @@ -2302,7 +2313,8 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue let mut report = json!({ "ok": false, "kind": kind_id(&e.kind), - "message": explained(&e.kind, &e.message), + "message": explained(e), + "messageOrigin": if e.authored { "script" } else { "built-in" }, "name": name, "line": e.line, "column": e.column, @@ -2395,6 +2407,12 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: /// The text of a failed run's error. fn failure_text(report: &Value) -> String { + let (before, after) = failure_frame(report); + format!("{before}{}{after}", report["message"].as_str().unwrap_or_default()) +} + +/// The text of a failed run's error before its message and after it. +fn failure_frame(report: &Value) -> (String, String) { let s = |k: &str| report[k].as_str().unwrap_or_default(); let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); let at = match report["file"].as_str() { @@ -2409,7 +2427,7 @@ fn failure_text(report: &Value) -> String { } else { String::new() }; - format!("{}{at}: {} ({}){kept}", s("name"), s("message"), s("kind")) + (format!("{}{at}: ", s("name")), format!(" ({}){kept}", s("kind"))) } /// A run's slice: the working copy in, the real session lent to the host functions, one measured diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 23dbe66e71..2c7b19ffbb 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -149,6 +149,7 @@ impl Session { global_edit_options: Default::default(), select_similar: crate::cmd::SIMILAR[0].0, keyboard_text: false, + toasts: Default::default(), script_key: None, script_engines: crate::script::EnginesKey::new(), script_stop: vectorcraft_js::Interrupt::new(), @@ -204,8 +205,7 @@ impl Session { let _ = self.finish_tool_edit_later(); // The switch goes on whatever the lent tool's last actions did, as for the deactivation. let _ = self.give_back_tool(view); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - let _ = self.apply_actions(acts); + let _ = self.deactivate_tool(view); // A batch leaves its interaction open in the document it leaves, to keep or roll back with // the rest of the batch; anything else in progress (a drag) is cancelled. if self.batch_stash.is_none() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1f118b31a3..38692e9056 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3393,6 +3393,149 @@ fn flare_rotation_turns_only_the_rays() { } } +/// A flare keeps its settings: `shape.editFlare` draws it again with the settings changed, in its +/// place and transformed as it has been since, as one undo step (none when nothing changes). A +/// flare with a changed part, a locked one and an expanded one are not edited. +#[test] +fn edit_flare_draws_a_transformed_flare_again_in_its_place_in_one_undo_step() { + let mut s = session(); + let p = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 9, "rings": 4, "x2": 400, "y2": 200, "seed": 3}); + let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap()); + // Reflected twice, sheared and back, turned a quarter and moved: it stays a flare. + for (c, p) in [ + ("object.reflect", json!({"axis": "vertical"})), + ("object.reflect", json!({"axis": "horizontal"})), + ("object.shear", json!({"angle": 30})), + ("object.shear", json!({"angle": -30})), + ("object.rotate", json!({"angle": 90})), + ("object.move", json!({"dx": 50, "dy": 10})), + ] { + s.execute(c, &p).unwrap(); + } + let spec = |s: &Session| flare_settings(&s.doc().unwrap().doc, id).expect("still a flare"); + let part = |s: &Session, name: &str| { + let g = s.doc().unwrap().doc.node(id).unwrap(); + g.children().unwrap().iter().filter(|c| c.name.as_deref() == Some(name)).map(|c| c.geometric_bounds().unwrap()).collect::>() + }; + let (c, e) = (spec(&s).center().unwrap(), spec(&s).end().unwrap()); + // The quarter turn made the rings run vertically, 200 points from the center. + assert!((c.distance(e) - 200.0).abs() < 1e-6 && (c.x - e.x).abs() < 1e-6, "{c:?} {e:?}"); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("shape.editFlare", &json!({"diameter": 100, "rings": 6, "rays": 0})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + let centre = part(&s, "Center")[0]; + assert!(centre.center().distance(c) < 1e-6 && (centre.width() - 100.0).abs() < 1e-6, "{centre:?}"); + assert_eq!((part(&s, "Ring").len(), part(&s, "Rays").len()), (6, 0)); + assert!(spec(&s).end().unwrap().distance(e) < 1e-6, "the end point stays"); + // Each ring lies on the line from the center to the end point. + assert!(part(&s, "Ring").iter().all(|r| (r.center().x - c.x).abs() < 1e-6), "{:?}", part(&s, "Ring")); + // The center handle, where it is drawn now: the end point stays where it is. + s.execute("shape.editFlare", &json!({"ids": [id.0], "cx": c.x + 20.0, "cy": c.y})).unwrap(); + assert!(spec(&s).center().unwrap().distance(Point::new(c.x + 20.0, c.y)) < 1e-6); + assert!(spec(&s).end().unwrap().distance(e) < 1e-6); + assert!(part(&s, "Center")[0].center().distance(Point::new(c.x + 20.0, c.y)) < 1e-6); + // The end handle, then the path length and direction. + s.execute("shape.editFlare", &json!({"x2": c.x + 20.0, "y2": c.y + 80.0})).unwrap(); + assert!(spec(&s).end().unwrap().distance(Point::new(c.x + 20.0, c.y + 80.0)) < 1e-6); + // The path length and direction are where the flare is drawn now, though it was turned. + s.execute("shape.editFlare", &json!({"direction": 0, "pathLength": 50})).unwrap(); + assert!(spec(&s).end().unwrap().distance(Point::new(c.x + 70.0, c.y)) < 1e-6, "{:?}", spec(&s).end()); + s.execute("edit.undo", &json!({})).unwrap(); + // Nothing changes: no undo step. + let undo = s.doc().unwrap().history.undo.len(); + s.execute("shape.editFlare", &json!({"diameter": 100})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + // Bad values are refused. + for bad in [json!({"rings": 2.5}), json!({"diameter": "big"}), json!({"cx": 10}), json!({"diameter": 1e20})] { + assert!(s.execute("shape.editFlare", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(spec(&s).end().unwrap().distance(e) < 1e-6, "undo puts the end point back"); + // A changed part: no longer a flare. + s.edit("Opacity", |d, _| { + let ring = d.node(id).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Center")).unwrap().id; + d.node_mut(ring).unwrap().opacity = 0.25; + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("shape.editFlare", &json!({"rings": 3})).unwrap_err().to_string(), "select a flare"); + s.execute("edit.undo", &json!({})).unwrap(); + // A locked flare. + s.execute("object.lock", &json!({})).unwrap(); + assert!(s.execute("shape.editFlare", &json!({"ids": [id.0], "rings": 3})).is_err()); + s.execute("object.unlockAll", &json!({})).unwrap(); + // Object › Expand: a plain group that is no longer a flare. + s.execute("object.expand", &json!({"object": true, "fill": false, "stroke": false})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().flare.is_none()); + assert!(s.execute("shape.editFlare", &json!({"rings": 3})).is_err()); +} + +/// `shape.flare` reads whole-number counts written as floats, and refuses fractions. +#[test] +fn flare_counts_are_whole_numbers() { + let mut s = session(); + let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 4.0, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + let g = s.doc().unwrap().doc.node(id).unwrap(); + let rays = g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Rays")).unwrap(); + assert_eq!(rays.path_data().unwrap().subpaths.len(), 4); + assert!(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 2.5})).is_err()); +} + +/// `shape.editFlare` on a flare scaled far down: a `pathLength`, an end point or a center that, +/// taken back to where the flare was drawn, is not a finite number is an error, and the flare keeps +/// its settings. +#[test] +fn edit_flare_end_points_that_are_not_finite_are_errors() { + let mut s = session(); + let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.scale", &json!({"sx": 1e-4, "sy": 1e-4})).unwrap(); + let before = flare_settings(&s.doc().unwrap().doc, id).expect("a flare"); + for (p, key) in [ + (json!({"pathLength": 1e305}), "x2"), + (json!({"x2": 1e305, "y2": 0}), "x2"), + (json!({"x2": 0, "y2": -1e305}), "y2"), + (json!({"cx": 1e305, "cy": 0}), "cx"), + ] { + let err = s.execute("shape.editFlare", &p).unwrap_err().to_string(); + assert!(err.ends_with(&format!("{key} must be a finite coordinate")), "{p}: {err}"); + assert_eq!(flare_settings(&s.doc().unwrap().doc, id).expect("still a flare"), before, "{p}"); + } +} + +/// A flare drawn again keeps its parts' pixel-aligned property, whatever the document's Align New +/// Objects to Pixel Grid is now, and a pixel-aligned flare that was moved is still a flare. +#[test] +fn edit_flare_keeps_its_parts_pixel_alignment() { + let mut s = session(); + let aligned = |s: &Session, id: NodeId| -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|c| c.extras().pixel_aligned).collect() + }; + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let on = NodeId(s.execute("shape.flare", &json!({"cx": 100.3, "cy": 200.6, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.move", &json!({"dx": 10.25, "dy": 3.5})).unwrap(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap(); + let part = |s: &Session, id: NodeId, name: &str| -> NodeId { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).unwrap().id + }; + let centre = part(&s, on, "Center"); + s.execute("shape.editFlare", &json!({"rings": 4})).unwrap(); + assert!(aligned(&s, on).len() > 4 && aligned(&s, on).iter().all(|a| *a)); + // Each part drawn again keeps its id and its own property: without the rays, the center does + // not take theirs. + assert_eq!(part(&s, on, "Center"), centre); + s.execute("object.setPixelAligned", &json!({"ids": [centre.0], "on": false})).unwrap(); + s.execute("select.set", &json!({"ids": [on.0]})).unwrap(); + s.execute("shape.editFlare", &json!({"rays": 0})).unwrap(); + let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned; + assert!(!node(&s, centre) && node(&s, part(&s, on, "Halo"))); + let off = NodeId(s.execute("shape.flare", &json!({"cx": 300.3, "cy": 200.6, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + s.execute("shape.editFlare", &json!({"rings": 4})).unwrap(); + assert!(aligned(&s, off).iter().all(|a| !*a)); +} + /// `shape.flare`'s `ringSeed` places the rings along the path anew and keeps their count and /// sizes and the other parts; the same `ringSeed` draws the same flare, neighboring ones differ, /// and a seed that is not a whole number of at least 0 (for `ringSeed`, below 2^53) is refused. @@ -3453,6 +3596,38 @@ fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() { assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}"); } +/// A flare drawn with a small `ringSeed` and then drawn again by `shape.editFlare` keeps its first +/// ring where `shape.flare` put it: the SplitMix64-initialized Xorshift64 stream's first value +/// along the path, for each seed. +#[test] +fn edit_flare_draws_the_first_ring_of_a_small_ring_seed_where_it_was() { + let first_t = |seed: u64| { + let mut z = seed.wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + let mut state = z ^ (z >> 31); + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 11) as f64 / (1u64 << 53) as f64 + }; + let ring_x = |s: &Session, id: NodeId| { + let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") }; + children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap().geometric_bounds().unwrap().center().x + }; + let mut s = session(); + for seed in [0, 1, 2, 5, 11] { + let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed}); + let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap()); + let expected = 20.0 + 1000.0 * first_t(seed); + assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: drawn at {}, expected {expected}", ring_x(&s, id)); + s.execute("shape.editFlare", &json!({"ids": [id.0], "opacity": 80})).unwrap(); + assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: drawn again at {}, expected {expected}", ring_x(&s, id)); + s.execute("shape.editFlare", &json!({"ids": [id.0], "opacity": 40})).unwrap(); + assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: a second edit keeps the ring"); + } +} + /// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew. #[test] fn ellipse_with_four_anchors_is_the_live_ellipse() { @@ -4329,6 +4504,124 @@ fn object_mosaic_refuses_a_boolean_given_as_text() { assert_eq!((r["tiles"].clone(), images(&s)), (json!(2), 1)); } +/// The size of the mosaic a call makes from the 100 × 50 pt image selected in `s`, with its column and row counts. +fn mosaic_size(s: &mut Session, p: serde_json::Value) -> (f64, f64, serde_json::Value, serde_json::Value) { + let image = s.doc().unwrap().selection.objects.clone(); + let r = s.execute("object.createObjectMosaic", &p).unwrap(); + let b = s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + s.execute("select.set", &json!({ "ids": image })).unwrap(); + ((b.width() * 1e6).round() / 1e6, (b.height() * 1e6).round() / 1e6, r["columns"].clone(), r["rows"].clone()) +} + +/// Resize Using Percentages reads the new width and height as percentages of the image's size; Constrain Ratio keeps +/// the image's proportions, the named side leading; Use Ratio makes the tiles square from the count on the +/// constrained side (columns by default), and the call answers the counts it used. +#[test] +fn object_mosaic_resizes_by_percentages_constrains_the_ratio_and_squares_the_tiles() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + assert_eq!(mosaic_size(&mut s, json!({"columns": 2, "rows": 1})), (100.0, 50.0, json!(2), json!(1))); + assert_eq!(mosaic_size(&mut s, json!({"width": 50, "height": 200, "percentages": true})), (50.0, 100.0, json!(10), json!(10))); + // A side left out is 100% of the image's. + assert_eq!(mosaic_size(&mut s, json!({"width": 150, "percentages": true})).0, 150.0); + assert_eq!(mosaic_size(&mut s, json!({"width": 200, "height": 10, "constrain": "width"})), (200.0, 100.0, json!(10), json!(10))); + assert_eq!(mosaic_size(&mut s, json!({"width": 10, "height": 25, "constrain": "height"})), (50.0, 25.0, json!(10), json!(10))); + assert_eq!(mosaic_size(&mut s, json!({"width": 50, "constrain": "width", "percentages": true})), (50.0, 25.0, json!(10), json!(10))); + // Square tiles: 10 columns of 10 pt over 50 pt are 5 rows; 4 rows of 12.5 pt over 100 pt are 8 columns. + assert_eq!(mosaic_size(&mut s, json!({"columns": 10, "rows": 3, "useRatio": true})), (100.0, 50.0, json!(10), json!(5))); + assert_eq!(mosaic_size(&mut s, json!({"columns": 3, "rows": 4, "useRatio": true, "constrain": "height"})), (100.0, 50.0, json!(8), json!(4))); + // A side named for Use Ratio is kept without Constrain Ratio: the size stays as given. + assert_eq!(mosaic_size(&mut s, json!({"rows": 4, "height": 100, "useRatio": "height"})), (100.0, 100.0, json!(4), json!(4))); + // On a new size: 30 columns over 300 × 50 pt are 5 rows. + assert_eq!(mosaic_size(&mut s, json!({"columns": 30, "width": 300, "useRatio": true})), (300.0, 50.0, json!(30), json!(5))); + // The count is kept within 1..1000. + assert_eq!(mosaic_size(&mut s, json!({"columns": 1, "width": 1, "height": 5000, "useRatio": true})).3, json!(1000)); + assert_eq!(mosaic_size(&mut s, json!({"columns": 1, "width": 5000, "height": 1, "useRatio": true})).3, json!(1)); + // A size under 0.1 pt grows in proportion while Constrain Ratio keeps it. + let (w, h, ..) = mosaic_size(&mut s, json!({"width": 0.1, "constrain": "width"})); + assert!((w - 0.2).abs() < 1e-6 && (h - 0.1).abs() < 1e-6, "{w} × {h}"); + // A side Constrain Ratio works out above 1,000,000 pt shrinks to it, in proportion: a height of + // 1,000,000 pt over the 100 × 50 pt image would need a width of 2,000,000 pt. + assert_eq!(mosaic_size(&mut s, json!({"height": 1e6, "constrain": "height"})), (1e6, 5e5, json!(10), json!(10))); + // An image 20,000,000 times wider than it is tall has no such size: the call is refused. + s.execute("object.scale", &json!({"sx": 1, "sy": 1e-7})).unwrap(); + let r = s.execute("object.createObjectMosaic", &json!({"width": 1e6, "constrain": "width"})); + let msg = "the image's proportions leave no size with both sides between 0.1 and 1000000 pt"; + assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == msg), "{r:?}"); +} + +/// Use Ratio squares the tiles as drawn: with 4 pt between columns, 10 columns of 10 pt cells draw 6 pt wide, so the +/// rows are 6 pt plus their own 4 pt apart (5 rows down 50 pt); on an image turned 90°, the tiles are measured along +/// its own axes. +#[test] +fn object_mosaic_use_ratio_takes_spacing_and_turned_images_into_account() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let image = s.doc().unwrap().selection.objects.clone(); + let counts = |s: &Session, p: serde_json::Value| crate::cmd::mosaic_counts(s, &p).unwrap(); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true, "spacingX": 4, "spacingY": 4})), (10, 5)); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true, "spacingX": 4})), (10, 8)); + assert_eq!(counts(&s, json!({"columns": 10, "rows": 7})), (10, 7), "without Use Ratio the counts are kept"); + let r = s.execute("object.createObjectMosaic", &json!({"columns": 10, "useRatio": true, "spacingX": 4})).unwrap(); + let g = s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone(); + let t = g.children().unwrap()[0].geometric_bounds().unwrap(); + assert!((t.width() - 6.0).abs() < 1e-6 && (t.height() - 6.25).abs() < 1e-6, "{t:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({ "ids": image })).unwrap(); + // Turned 90°, the image's 100 pt side runs down the page; 10 columns along it are still 5 rows across its 50. + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true})), (10, 5)); +} + +#[test] +fn object_mosaic_square_count_is_the_nearest_whole_count() { + use crate::cmd::menucmds::mosaic_square_count; + assert_eq!(mosaic_square_count(10, 100.0, 50.0, 0.0, 0.0), 5); + assert_eq!(mosaic_square_count(3, 100.0, 50.0, 0.0, 0.0), 2); + assert_eq!(mosaic_square_count(0, 100.0, 50.0, 0.0, 0.0), 1); + assert_eq!(mosaic_square_count(10, 0.0, 50.0, 0.0, 0.0), 1); + assert_eq!(mosaic_square_count(1000, 1.0, 1000.0, 0.0, 0.0), 1000); + // Spacing wider than a cell leaves 10% of it, on either side. + assert_eq!(mosaic_square_count(10, 100.0, 50.0, 50.0, 0.0), 50); + // 10 columns of 1 pt tiles (9 pt gaps) over 100 pt; rows 100 pt apart are capped too, so 10 rows draw 1 pt. + assert_eq!(mosaic_square_count(10, 100.0, 100.0, 9.0, 100.0), 10); + // 15 pt tiles over 50 pt: 3 rows draw 16.7 pt and 4 rows 12.5 pt, so 3. + assert_eq!(mosaic_square_count(1, 15.0, 50.0, 0.0, 0.0), 3); +} + +/// A Constrain Ratio side that is not "width" or "height", a new size of 0 or less, and Use Ratio or Resize Using +/// Percentages given as text are errors naming the key; no mosaic is made. +#[test] +fn object_mosaic_refuses_a_bad_ratio_side_size_or_switch() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + for (p, msg) in [ + (json!({"constrain": "both"}), "`constrain` must be one of \"width\", \"height\" or null"), + (json!({"constrain": 1}), "`constrain` must be one of \"width\", \"height\" or null"), + (json!({"width": 0}), "`width` must be between 0.1 and 1000000 (got 0)"), + (json!({"height": -5, "percentages": true}), "`height` must be between 0.1 and 1000000 (got -5)"), + (json!({"width": 2e6, "percentages": true}), "`width` must be between 0.1 and 1000000 (got 2000000)"), + // A side Constrain Ratio works out is not used, but a size given for it is still checked. + (json!({"width": 200, "height": 0, "constrain": "width"}), "`height` must be between 0.1 and 1000000 (got 0)"), + (json!({"useRatio": "true"}), "`useRatio` must be one of \"width\", \"height\", true, false or null"), + (json!({"useRatio": 1}), "`useRatio` must be one of \"width\", \"height\", true, false or null"), + (json!({"percentages": 1}), "`percentages` must be true or false"), + ] { + let r = s.execute("object.createObjectMosaic", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == msg), "{p}: {r:?}"); + assert_eq!(undo(&s), before, "{p}"); + } + let r = s.execute("object.createObjectMosaic", &json!({"constrain": null, "useRatio": null, "percentages": null})).unwrap(); + assert_eq!(r["tiles"], json!(100)); +} + #[test] fn snap_to_pixel_rounds_drawing_and_moves() { let mut s = session(); diff --git a/crates/engine/src/tests/anchor_edit_work.rs b/crates/engine/src/tests/anchor_edit_work.rs index 5401bc0bf8..5130d30c26 100644 --- a/crates/engine/src/tests/anchor_edit_work.rs +++ b/crates/engine/src/tests/anchor_edit_work.rs @@ -176,3 +176,61 @@ fn a_handle_already_in_place_on_a_smooth_anchor_records_no_undo_step() { .unwrap(); assert_eq!(undo_steps(&s), 1); } + +/// `path.setHandle` with `link` makes a corner smooth: the other handle turns in line at its own +/// length, a retracted one is pulled out to the moved handle's length where a segment leaves the +/// anchor on its side and stays retracted at an open end. A handle already in place on a corner +/// still links; a request that changes nothing records no undo step; `link` that is not a boolean +/// or goes with `independent` is refused. +#[test] +fn a_linked_handle_makes_the_anchor_smooth() { + let (mut s, id) = long_path(100); + let p = anchor(&s, id, 5).p; + let corner = Anchor { p, h_in: p + Vec2::new(-6.0, 8.0), h_out: p + Vec2::new(3.0, 0.0), kind: AnchorKind::Corner }; + let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap(); + path.subpaths[0].anchors[5] = corner; + let link = |x: f64, y: f64, ai: usize| json!({"id": id.0, "anchor": ai, "which": "out", "x": x, "y": y, "link": true}); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + + // The out handle stays where it is; the corner becomes smooth, the in handle turned opposite it. + s.execute("path.setHandle", &link(corner.h_out.x, corner.h_out.y, 5)).unwrap(); + assert_eq!(undo_steps(&s), 1); + let a = anchor(&s, id, 5); + assert_eq!((a.kind, a.h_out), (AnchorKind::Smooth, corner.h_out)); + assert!(near(a.h_in, p + Vec2::new(-10.0, 0.0)), "{a:?}"); + // Moved: the in handle keeps its length of 10. + let to = p + Vec2::new(4.0, 3.0); + s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap(); + assert_eq!(undo_steps(&s), 2); + let a = anchor(&s, id, 5); + assert!(a.kind == AnchorKind::Smooth && a.h_out == to && near(a.h_in, p + Vec2::new(-8.0, -6.0)), "{a:?}"); + // The same request again changes nothing. + s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap(); + assert_eq!(undo_steps(&s), 2); + + // A retracted in handle on an inner anchor is pulled out; at the open start it stays retracted. + let q = anchor(&s, id, 7).p; + s.execute("path.setHandle", &link(q.x, q.y + 5.0, 7)).unwrap(); + let a = anchor(&s, id, 7); + assert!(a.kind == AnchorKind::Smooth && near(a.h_in, q + Vec2::new(0.0, -5.0)), "{a:?}"); + let q = anchor(&s, id, 0).p; + s.execute("path.setHandle", &link(q.x, q.y + 5.0, 0)).unwrap(); + let a = anchor(&s, id, 0); + assert!(a.kind == AnchorKind::Smooth && a.h_in == q && a.h_out == q + Vec2::new(0.0, 5.0), "{a:?}"); + + let before = s.doc().unwrap().doc.clone(); + let undo = undo_steps(&s); + for bad in [ + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": "yes"}), + 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": 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}), + ] { + assert!(s.execute("path.setHandle", &bad).is_err(), "{bad}"); + } + assert!(s.doc().unwrap().doc == before, "a refused request changed the document"); + assert_eq!(undo_steps(&s), undo); +} diff --git a/crates/engine/src/tests/attributes.rs b/crates/engine/src/tests/attributes.rs index b6d00111e2..35dda8656b 100644 --- a/crates/engine/src/tests/attributes.rs +++ b/crates/engine/src/tests/attributes.rs @@ -90,6 +90,23 @@ fn values_that_differ_read_null_and_recent_urls_keep_the_newest_first() { assert_eq!(info(&mut s, json!({"ids": [p.0, a.0]}))["showCenter"], Value::Null); } +/// The recent URLs keep the 30 newest distinct URLs, the most the panel's URL menu can list, and +/// a URL given again moves to the front without taking a second place. +#[test] +fn recent_urls_keep_the_thirty_newest() { + let mut s = session(); + rect(&mut s, 0.0); + for i in 0..35 { + run(&mut s, "attributes.set", json!({"url": format!("https://example.com/{i}")})); + } + let want: Vec = (5..35).rev().map(|i| format!("https://example.com/{i}")).collect(); + assert_eq!(info(&mut s, json!({}))["recentUrls"], json!(want)); + run(&mut s, "attributes.set", json!({"url": "https://example.com/20"})); + let urls = info(&mut s, json!({}))["recentUrls"].as_array().unwrap().clone(); + assert_eq!((urls.len(), urls[0].as_str(), urls[1].as_str()), (30, Some("https://example.com/20"), Some("https://example.com/34"))); + assert_eq!(urls.iter().filter(|u| *u == "https://example.com/20").count(), 1); +} + /// A five-pointed star drawn as one self-intersecting path (its centre is wound twice). fn star(s: &mut Session) -> NodeId { let (c, r) = (50.0f64, 45.0f64); diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index c22eb188b7..7f7c7fffa4 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -431,3 +431,35 @@ fn a_spine_segment_bends_with_perpendicular_handles() { use vectorcraft_geom::kurbo::ParamCurve; assert!(sp.segment(0).eval(0.5).distance(Point::new(55.0, 45.0)) < 1e-9, "{sp:?}"); } + +/// `link` with `handle` makes a spine point smooth, the other handle in line opposite the moved +/// one, without moving the keys; the same request again records no undo step, and `link` that is +/// not a boolean, goes with `independent` or comes without `handle` is refused. +#[test] +fn a_linked_spine_handle_makes_the_point_smooth() { + let mut s = session(); + let (_, _, g) = blend(&mut s); + s.execute("object.blend.spine.addAnchor", &json!({"x": 55, "y": 5})).unwrap(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let link = json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true}); + s.execute("object.blend.spine.moveAnchor", &link).unwrap(); + let a = spec(&s, g).spine.unwrap().subpaths[0].anchors[1]; + assert_eq!((a.kind, a.h_out), (vectorcraft_geom::AnchorKind::Smooth, Point::new(75.0, 25.0))); + let (din, dout) = (a.h_in - a.p, a.h_out - a.p); + assert!(din.hypot() > 1e-6 && (din.normalize() + dout.normalize()).hypot() < 1e-9, "{a:?}"); + let st = steps(&s, g); + assert_eq!((center(&st[0]), center(&st[2])), (Point::new(5.0, 5.0), Point::new(105.0, 5.0)), "the keys stay put"); + let done = undo(&s); + s.execute("object.blend.spine.moveAnchor", &link).unwrap(); + assert_eq!(undo(&s), done, "an unchanged spine recorded an undo step"); + let before = spec(&s, g); + 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, "x": 75, "y": 25, "link": true}), + ] { + assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}"); + } + assert_eq!(spec(&s, g), before); + assert_eq!(undo(&s), done); +} diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index f960ca91d3..38aadcc712 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -117,7 +117,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "game-trails", "energy-beams", "dry-media", - "tech-circuit" + "tech-circuit", + "arrows" ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); @@ -145,6 +146,12 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] ); assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4))); + let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"})); + assert_eq!( + arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), + [("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")] + ); + assert_eq!((libs[11]["name"].as_str(), libs[11]["count"].as_u64()), (Some("Arrows"), Some(5))); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); @@ -162,6 +169,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("game-trails", "art"), ("energy-beams", "art"), ("dry-media", "art"), + ("arrows", "art"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); @@ -220,6 +228,78 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer { vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0) } +#[test] +fn arrows_library_lists_renders_and_applies_original_brushes() { + let mut s = session(); + let listed = run(&mut s, "brush.libraries", json!({})); + let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "arrows").unwrap(); + assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Arrows"), Some("builtIn"), Some(5))); + let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap(); + assert_eq!( + lib.brushes.iter().map(|b| (b.name.as_str(), b.kind.type_id())).collect::>(), + [("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")] + ); + for b in &lib.brushes { + for length in [2.0, 200.0] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke()); + let pts = anchors(&pieces.iter().collect::>()); + assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name); + } + } + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap(); + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Double Arrow", "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), ["Double Arrow"]); + assert_eq!(added["applied"], json!([path])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some("Double Arrow")); + run(&mut s, "edit.undo", json!({})); + assert!(vectorcraft_brush::find(doc(&s), "Double Arrow").is_none()); + run(&mut s, "edit.redo", json!({})); + assert_eq!(brush(&s, "Double Arrow"), lib.brushes[2]); +} + +#[test] +fn the_chevron_arrows_second_chevron_keeps_its_length_on_a_long_path() { + let s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap(); + let b = lib.brush("Chevron Arrow").unwrap(); + let widths = |length: f64| { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke()); + let children = pieces[0].children().unwrap(); + assert_eq!(children.len(), 3, "shaft, head and second chevron"); + children[1..].iter().map(|n| n.geometric_bounds().unwrap().width()).collect::>() + }; + let short = widths(100.0); + for (long, short) in widths(400.0).into_iter().zip(short) { + assert!((long - short).abs() < 1e-6, "the heads keep their length: {long} on 400 pt, {short} on 100 pt"); + } +} + +#[test] +fn dashed_arrow_keeps_separate_dashes_and_survives_library_save() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap(); + let b = lib.brush("Dashed Arrow").unwrap(); + let mut curve = line_to(40.0); + curve.curve_to((60.0, -40.0), (140.0, 40.0), (200.0, 0.0)); + for path in [line_to(2.0), line_to(200.0), curve] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()); + let pts = anchors(&pieces.iter().collect::>()); + assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite())); + } + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(200.0), &black_stroke()); + let children = pieces[0].children().unwrap(); + assert_eq!(children.len(), 6, "five separate dashes and one head"); + let bounds: Vec<_> = children.iter().map(|n| n.geometric_bounds().unwrap()).collect(); + assert!(bounds.windows(2).all(|p| p[0].x1 < p[1].x0), "the dashes and head remain separated"); + run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Dashed Arrow"})); + let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Dashed Arrow"]})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::find(&reopened, "Dashed Arrow").unwrap(), *b); +} + /// Original circuit art and repeat tiles survive adding, applying and saving a library. #[test] fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() { diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index dfab5336de..33483c5e21 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -5027,6 +5027,73 @@ fn live_paint_does_not_count_art_named_like_its_parts() { } } +/// A path drawn in an isolated Live Paint group can't be named Face or Edge, the names of the +/// group's faces and edges: `object.setProps` and `layer.setProps` return an error and rename +/// nothing, so Gap Options and a path dragged into the group keep the path. A face keeps its name. +#[test] +fn live_paint_refuses_part_names_for_paths_drawn_in_it() { + use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, faces}; + let mut s = session(); + let g = live(&mut s); + let face = faces(&node(&s, g))[0].id; + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let a = line_across(&mut s, 50.0); + // Hidden, the path stays in the group as drawn when isolation mode ends. + s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + for name in [FACE_NAME, EDGE_NAME] { + let calls = [ + ("object.setProps", json!({"id": a.0, "name": name})), + ("layer.setProps", json!({"id": a.0, "name": name})), + ("layer.setProps", json!({"ids": [face.0, a.0], "name": name})), + ]; + for (c, p) in calls { + let err = s.execute(c, &p).unwrap_err().to_string(); + assert!(err.contains("give the path another name"), "{c} {p}: {err}"); + } + } + assert!(s.doc().unwrap().doc == before.0, "nothing was renamed"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + s.execute("layer.setProps", &json!({"id": face.0, "name": FACE_NAME})).unwrap(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the hidden path stays in the group"); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "Gap Options keeps the path"); + let b = line_to_right_face(&mut s, 30.0); + s.execute("layer.move", &json!({"ids": [b.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path dragged in keeps it"); + assert_eq!(faces(&node(&s, g)).len(), 5); +} + +/// A path pasted into an isolated Live Paint group under the name of a face or an edge loses the +/// name, so Gap Options keeps it and it joins the group's paths when isolation mode ends. +#[test] +fn live_paint_paste_clears_part_names() { + use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, faces, sources}; + for name in [FACE_NAME, EDGE_NAME] { + let mut s = session(); + let g = live(&mut s); + let r = rect(&mut s, 20.0, 40.0, 60.0, 20.0); + s.execute("object.setProps", &json!({"id": r.0, "name": name})).unwrap(); + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + s.execute("edit.pasteInPlace", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.clone(); + assert_eq!(pasted.len(), 1); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(pasted[0]), Some(g), "{name}: the paste goes into the group"); + assert_eq!(d.node(pasted[0]).unwrap().name, None, "{name}: the paste loses the name"); + assert_eq!(d.node(r).unwrap().name.as_deref(), Some(name), "the path outside keeps its name"); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(pasted[0]), Some(g), "{name}: Gap Options keeps the paste"); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(pasted[0]), Some(sources(&n).unwrap().id), "{name}: the paste joined"); + assert!(faces(&n).len() > 3); + } +} + /// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group /// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and /// joins the group with the tile saved. @@ -5098,6 +5165,315 @@ fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() { } } +/// With Live Paint group `inner` made in isolated Live Paint group `outer` and then isolated itself, +/// leaving both levels (`object.exitIsolation`, or `object.isolate` on the layer) adds the path drawn +/// in `inner` to it and then `inner` and the path drawn directly in `outer` to `outer`, one undo step +/// each. Isolating `outer` from `inner` adds only `inner`'s drawn path, and `outer` keeps its own. +#[test] +fn live_paint_isolation_merges_nested_live_paint_groups_it_leaves() { + use vectorcraft_tools::builder::{faces, sources}; + for to in ["exit", "layer", "outer"] { + let mut s = session(); + let outer = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(outer).unwrap(); + s.execute("object.isolate", &json!({"id": outer.0})).unwrap(); + let a = line_across(&mut s, 50.0); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(outer)); + let inner = live(&mut s); + assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(outer), "the inner group is drawn in the outer one"); + s.execute("object.isolate", &json!({"id": inner.0})).unwrap(); + let b = line_across(&mut s, 30.0); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(inner)); + let steps = s.doc().unwrap().history.undo.len(); + match to { + "exit" => s.execute("object.exitIsolation", &json!({})).unwrap(), + "layer" => s.execute("object.isolate", &json!({"id": layer.0})).unwrap(), + _ => s.execute("object.isolate", &json!({"id": outer.0})).unwrap(), + }; + let d = &s.doc().unwrap().doc; + if to == "outer" { + assert_eq!(s.doc().unwrap().isolation, Some(outer)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the inner group's path joins"); + let n = node(&s, inner); + assert_eq!(d.parent_of(b), Some(sources(&n).unwrap().id), "the path drawn in the inner group joined it"); + assert_eq!(d.parent_of(inner), Some(outer), "the inner group stays drawn in the outer one"); + assert_eq!(d.parent_of(a), Some(outer), "the path drawn in the outer group stays as drawn"); + continue; + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{to}: one undo step for each group"); + assert!(d.node(inner).is_none(), "{to}: the inner group joined the outer one"); + let n = node(&s, outer); + let src = sources(&n).unwrap().id; + assert_eq!(d.parent_of(a), Some(src), "{to}: the path drawn in the outer group joined it"); + assert!(d.ancestry(b).unwrap().contains(&src), "{to}: the path drawn in the inner group is among the outer group's paths"); + assert!(n.children().unwrap().iter().all(|c| c.id == src || c.path_data().is_some()), "{to}: only parts are left in the outer group"); + assert!(faces(&n).len() > 3, "{to}: the added paths cut the outer group's faces"); + if to == "exit" { + assert_eq!(s.doc().unwrap().selection.objects, vec![outer]); + } + } +} + +/// A line from left of the [`live`] group to its right face, so it cuts the two faces left of it. +fn line_to_right_face(s: &mut Session, y: f64) -> NodeId { + let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn undo_label(s: &Session) -> Option { + s.doc().unwrap().history.undo.last().map(|e| e.label.clone()) +} + +/// Paths dragged into a Live Paint group in the Layers panel join its paths as Live Paint › Merge +/// adds them: they go among its sources and cut the faces they cross, a painted face they do not +/// cross keeps its fill, and the drop is one "Merge Live Paint" undo step that selects the group. +#[test] +fn layers_drag_adds_paths_to_a_live_paint_group() { + use vectorcraft_tools::builder::{face_at, faces, sources}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap(); + let layer = s.doc().unwrap().doc.parent_of(g); + let (a, b) = (line_to_right_face(&mut s, 30.0), line_to_right_face(&mut s, 70.0)); + assert_eq!(s.doc().unwrap().doc.parent_of(a), layer); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("layer.move", &json!({"ids": [a.0, b.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(r["ids"], json!([g.0]), "the rows that joined are listed as the group"); + let d = s.doc().unwrap(); + assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step"); + assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint")); + assert_eq!(s.doc().unwrap().selection.objects, vec![g]); + let n = node(&s, g); + let src = sources(&n).unwrap(); + assert_eq!(src.children().unwrap().len(), 4); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources"); + } + assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three"); + assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 3); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), layer, "Undo puts {id} back where it was"); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 7); +} + +/// A path named like a Live Paint group's sources group joins the group when it is dragged in, in +/// front of the sources group or behind it: the group keeps its own sources group and the path +/// goes among its paths. +#[test] +fn layers_drag_of_a_path_named_like_the_sources_group_joins_a_live_paint_group() { + use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources}; + for index in [0, 99] { + let mut s = session(); + let g = live(&mut s); + let a = line_to_right_face(&mut s, 30.0); + s.execute("object.setProps", &json!({"id": a.0, "name": SOURCES_NAME})).unwrap(); + s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": index})).unwrap(); + assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"), "index {index}"); + let n = node(&s, g); + let src = sources(&n).unwrap(); + assert!(src.children().is_some(), "index {index}: the sources group is a group"); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(src.id), "index {index}: the path joined the sources"); + assert_eq!(faces(&n).len(), 5, "index {index}"); + } +} + +/// An object drawn in a Live Paint group and named like its sources group can be moved ahead of the +/// sources group: the group keeps its own sources group and stays a Live Paint group. +#[test] +fn layers_reorder_of_an_object_named_like_the_sources_group_keeps_the_live_paint_group() { + use vectorcraft_tools::builder::{SOURCES_NAME, is_live_paint, sources}; + let mut s = session(); + let g = live(&mut s); + let real = sources(&node(&s, g)).unwrap().id; + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let a = line_across(&mut s, 50.0); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g)); + s.execute("object.setProps", &json!({"id": a.0, "name": SOURCES_NAME})).unwrap(); + s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": 0})).unwrap(); + let n = node(&s, g); + assert!(is_live_paint(&n)); + assert_eq!(sources(&n).unwrap().id, real); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the object stays where it was drawn"); +} + +/// A path named `Face` that is dragged into a Live Paint group is not one of its faces: the face it +/// covers keeps its own fill. +#[test] +fn layers_drag_of_a_path_named_face_does_not_repaint_the_group() { + use vectorcraft_tools::builder::{face_at, faces}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#00ff00"})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 50.0, 100.0); + set_fill(&mut s, a, Color::rgb(0.0, 0.0, 1.0)); + s.execute("object.setProps", &json!({"id": a.0, "name": "Face"})).unwrap(); + s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": 99})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 3); + assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.fill_paint(), green); +} + +/// An Alt-drag into a Live Paint group adds a copy and leaves the path where it was; a drop above +/// one of the group's faces, and `node.move` into the group, add the path the same way. +#[test] +fn layers_drag_copy_and_drop_beside_a_part_add_to_a_live_paint_group() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g); + let a = line_to_right_face(&mut s, 30.0); + s.execute("layer.move", &json!({"ids": [a.0], "target": g.0, "copy": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), layer, "the path itself stays"); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 5); + let src = sources(&n).unwrap().children().unwrap().clone(); + assert_eq!(src.len(), 3); + assert!(src.iter().all(|c| c.id != a), "a copy joined"); + let (face, other_face) = (faces(&n)[0].id, faces(&n)[1].id); + let b = line_to_right_face(&mut s, 70.0); + // A face dragged along is made again with the others, so only the group is listed. + let r = s.execute("layer.move", &json!({"ids": [b.0, other_face.0], "target": face.0, "place": "above"})).unwrap(); + assert_eq!(r["ids"], json!([g.0])); + assert_eq!(s.doc().unwrap().layer_rows, vec![g]); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(sources(&n).unwrap().id), "a drop beside a face joins"); + assert_eq!(faces(&n).len(), 7); + let c = line_to_right_face(&mut s, 50.0); + s.execute("node.move", &json!({"id": c.0, "parent": g.0, "index": 0})).unwrap(); + assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint")); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(c), Some(sources(&n).unwrap().id), "node.move into the group joins"); + assert_eq!(faces(&n).len(), 9); +} + +/// Dragging type, or type with a path, into a Live Paint group is refused with Make's message and +/// moves nothing, as Merge refuses it; a drop beside the group is an ordinary move. +#[test] +fn layers_drag_refuses_type_into_a_live_paint_group() { + use vectorcraft_tools::builder::faces; + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g); + let a = line_to_right_face(&mut s, 30.0); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + for p in [json!({"ids": [a.0, text.0], "target": g.0}), json!({"ids": [text.0], "target": g.0, "copy": true})] { + let err = s.execute("layer.move", &p).unwrap_err().to_string(); + assert!(err.contains("Live Paint takes paths and compound paths"), "{err}"); + } + assert!(s.execute("node.move", &json!({"id": text.0, "parent": g.0, "index": 0})).is_err()); + assert!(s.doc().unwrap().doc == before.0, "nothing moved"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + s.execute("layer.move", &json!({"ids": [a.0, text.0], "target": g.0, "place": "above"})).unwrap(); + assert_eq!(undo_label(&s).as_deref(), Some("Move Rows")); + assert_eq!(s.doc().unwrap().doc.parent_of(text), layer); + assert_eq!(faces(&node(&s, g)).len(), 3); +} + +/// A path dragged out of a Live Paint group's sources leaves its faces and edges: the group makes +/// them again from the paths left, and with none left it has no faces until a path joins it again. +/// Reordering the sources, or the group's own faces, makes nothing again. +#[test] +fn layers_drag_out_of_a_live_paint_group_makes_its_faces_again() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + let n = node(&s, g); + let src: Vec = sources(&n).unwrap().children().unwrap().iter().map(|c| c.id).collect(); + let face_ids: Vec = faces(&n).iter().map(|f| f.id).collect(); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": src[1].0, "place": "above"})).unwrap(); + s.execute("layer.move", &json!({"ids": [face_ids[0].0], "target": face_ids[2].0, "place": "above"})).unwrap(); + let n = node(&s, g); + assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2, "a reorder keeps the sources"); + let mut now: Vec = faces(&n).iter().map(|f| f.id).collect(); + now.sort(); + let mut was = face_ids.clone(); + was.sort(); + assert_eq!(now, was, "and the faces"); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": layer.0})).unwrap(); + assert_eq!(undo_label(&s).as_deref(), Some("Move Rows")); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(src[0]), Some(layer)); + assert_eq!(sources(&n).unwrap().children().unwrap().len(), 1); + assert_eq!(faces(&n).len(), 1, "one rectangle left"); + s.execute("node.move", &json!({"id": src[1].0, "parent": layer.0, "index": 0})).unwrap(); + let n = node(&s, g); + assert!(vectorcraft_tools::builder::is_live_paint(&n), "the group stays a Live Paint group"); + assert!(sources(&n).unwrap().children().unwrap().is_empty()); + assert!(faces(&n).is_empty() && vectorcraft_tools::builder::edges(&n).is_empty()); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 1, "a path joins the empty group"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 1); +} + +/// A path dragged from a Live Paint group's sources into the group itself stays among its paths, +/// and the faces it bounds keep their paint, also when it is the group's only path. +#[test] +fn layers_drag_a_source_path_into_its_own_live_paint_group_keeps_the_paint() { + use vectorcraft_tools::builder::{face_at, faces, sources}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#00ff00"})).unwrap(); + let src: Vec = sources(&node(&s, g)).unwrap().children().unwrap().iter().map(|c| c.id).collect(); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0, "place": "inside"})).unwrap(); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(src[0]), Some(sources(&n).unwrap().id), "the path stays among the group's paths"); + assert_eq!(faces(&n).len(), 3); + assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face it bounds keeps its fill"); + s.execute("layer.move", &json!({"ids": [src[1].0], "target": layer.0})).unwrap(); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [50, 50], "color": "#0000ff"})).unwrap(); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0, "place": "inside"})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 1); + assert_eq!(face_at(&n, Point::new(50.0, 50.0)).unwrap().appearance.fill_paint(), blue, "the only path's face keeps its fill"); +} + +/// A Live Paint group among another Live Paint group's paths gives it faces and edges: a path +/// dragged into or out of the inner group's paths, or from the outer group's paths into the inner +/// group's, makes the inner group's faces and edges again and then the outer group's. +#[test] +fn layers_drag_into_a_nested_live_paint_group_makes_the_outer_group_again() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let outer = live(&mut s); + let inner = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(outer).unwrap(); + let first_source = |s: &Session, g: NodeId| sources(&node(s, g)).unwrap().children().unwrap()[0].id; + let into = |s: &mut Session, row: NodeId, g: NodeId| { + let target = first_source(s, g); + s.execute("layer.move", &json!({"ids": [row.0], "target": target.0, "place": "above"})).unwrap(); + }; + into(&mut s, inner, outer); + assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(sources(&node(&s, outer)).unwrap().id)); + let plain = faces(&node(&s, outer)).len(); + let a = line_to_right_face(&mut s, 30.0); + into(&mut s, a, inner); + assert_eq!(faces(&node(&s, inner)).len(), 5); + let cut = faces(&node(&s, outer)).len(); + assert!(cut > plain, "a path joining the inner group cuts the outer group's faces: {cut} faces, {plain} before"); + s.execute("layer.move", &json!({"ids": [a.0], "target": layer.0})).unwrap(); + assert_eq!(faces(&node(&s, inner)).len(), 3); + assert_eq!(faces(&node(&s, outer)).len(), plain, "a path leaving the inner group leaves the outer group's faces"); + into(&mut s, a, outer); + assert_eq!(faces(&node(&s, outer)).len(), cut); + into(&mut s, a, inner); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&node(&s, inner)).unwrap().id)); + assert_eq!(faces(&node(&s, inner)).len(), 5); + assert_eq!(faces(&node(&s, outer)).len(), cut, "the outer group is made after the inner one"); +} + /// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and /// graphic style link, and return it as it then is. fn dress_live_group(s: &mut Session, g: NodeId) -> Node { diff --git a/crates/engine/src/tests/compound_shape.rs b/crates/engine/src/tests/compound_shape.rs index 3f027254b0..0057af9253 100644 --- a/crates/engine/src/tests/compound_shape.rs +++ b/crates/engine/src/tests/compound_shape.rs @@ -696,3 +696,108 @@ fn a_locked_or_hidden_layer_keeps_the_isolated_compound_shape_from_clicks() { assert!(selected(&s).is_empty(), "{prop}: nor by a marquee"); } } + +/// A straight line, closed as a compound shape closes open paths, encloses no area, so it +/// contributes no area to the shape: Make Compound Shape still makes it, in any mode and at any +/// place in the stack, and its reply carries a warning that names Outline Stroke. The shape draws +/// the area the other members make in that mode: the square alone in Add, or on top in Subtract, +/// and nothing in Intersect or when the line is the backmost member in Subtract. A line in a group, +/// beside a closed path too, an open evenodd square traced twice, and open evenodd subpaths that cancel one another or a closed +/// subpath of the same path are the same. An open path that encloses an area once closed (a bow tie +/// whose lobes cancel in signed area included) and closed shapes alone give no warning (#7849). +#[test] +fn lines_that_add_no_area_are_reported() { + use crate::cmd::OPEN_PATHS_ADD_NO_AREA; + fn line_of(s: &mut Session) -> NodeId { + NodeId(run(s, "shape.line", json!({"x1": 20, "y1": 50, "x2": 180, "y2": 50}))["id"].as_u64().unwrap()) + } + fn vee_of(s: &mut Session) -> NodeId { + let anchors = json!([{"x": 20, "y": 50}, {"x": 100, "y": 150}, {"x": 180, "y": 50}]); + NodeId(run(s, "path.create", json!({ "anchors": anchors }))["id"].as_u64().unwrap()) + } + fn bow_tie_of(s: &mut Session) -> NodeId { + let anchors = json!([{"x": 20, "y": 0}, {"x": 180, "y": 100}, {"x": 180, "y": 0}, {"x": 20, "y": 100}]); + NodeId(run(s, "path.create", json!({ "anchors": anchors }))["id"].as_u64().unwrap()) + } + fn twice_around_of(s: &mut Session) -> NodeId { + let d = "M20 20 L80 20 L80 80 L20 80 L20 20 L80 20 L80 80 L20 80"; + let id = NodeId(run(s, "path.create", json!({ "d": d }))["id"].as_u64().unwrap()); + run(s, "path.setFillRule", json!({"rule": "evenOdd"})); + id + } + fn evenodd_of(s: &mut Session, d: &str) -> NodeId { + let id = NodeId(run(s, "path.create", json!({ "d": d }))["id"].as_u64().unwrap()); + run(s, "path.setFillRule", json!({"rule": "evenOdd"})); + id + } + fn two_open_squares_of(s: &mut Session) -> NodeId { + evenodd_of(s, "M20 20 L80 20 L80 80 L20 80 M20 20 L80 20 L80 80 L20 80") + } + fn open_over_closed_of(s: &mut Session) -> NodeId { + evenodd_of(s, "M20 20 L80 20 L80 80 L20 80 Z M20 20 L80 20 L80 80 L20 80") + } + fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId { + run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::>()})); + NodeId(run(s, "object.group", json!({}))["id"].as_u64().unwrap()) + } + type Build = fn(&mut Session) -> NodeId; + // (case, mode, the other member, whether it goes behind the 100 pt square, warned, area drawn) + type Case = (&'static str, &'static str, Build, bool, bool, Option); + let cases: [Case; 13] = [ + ("an open evenodd square traced twice", "add", twice_around_of, false, true, Some(10_000.0)), + ("two open evenodd squares on one another", "add", two_open_squares_of, false, true, Some(10_000.0)), + ("an open evenodd square on the same closed square", "add", open_over_closed_of, false, true, Some(10_000.0)), + ("a line", "add", line_of, false, true, Some(10_000.0)), + ("a line, subtracting", "subtract", line_of, false, true, Some(10_000.0)), + ("a line, intersecting", "intersect", line_of, false, true, Some(0.0)), + ("a line behind, subtracting", "subtract", line_of, true, true, Some(0.0)), + ( + "a group of lines", + "add", + |s| { + let ids = [line_of(s), line_of(s)]; + group_of(s, &ids) + }, + false, + true, + Some(10_000.0), + ), + ( + "a group of a line and a square", + "add", + |s| { + let ids = [line_of(s), square(s, 200.0, "#00ff00")]; + group_of(s, &ids) + }, + false, + true, + Some(20_000.0), + ), + ("an open path that encloses an area", "add", vee_of, false, false, None), + ("an open bow tie, whose signed area is zero", "add", bow_tie_of, false, false, None), + ("a square", "add", |s| square(s, 50.0, "#0000ff"), false, false, Some(15_000.0)), + ("a square, subtracting", "subtract", |s| square(s, 50.0, "#0000ff"), false, false, Some(5_000.0)), + ]; + for (what, mode, build, behind, warned, want) in cases { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + let (back, front) = if behind { + let other = build(&mut s); + (other, square(&mut s, 0.0, "#ff0000")) + } else { + let sq = square(&mut s, 0.0, "#ff0000"); + (sq, build(&mut s)) + }; + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let r = run(&mut s, "object.compoundShape.make", json!({ "mode": mode })); + let id = NodeId(r["id"].as_u64().unwrap_or_else(|| panic!("{what}: {r}"))); + assert_eq!(node(&s, id).children().unwrap().len(), 2, "{what}: both are members"); + assert_eq!(r.get("warning").and_then(Value::as_str), warned.then_some(OPEN_PATHS_ADD_NO_AREA), "{what}: {r}"); + if let Some(want) = want { + let d = &s.doc().unwrap().doc; + let hook = |c: &Node| effects::outline_object(Some(d), c); + let got = effects::compound_shape_area(None, &node(&s, id), Some(&hook)).map_or(0.0, |p| area(&p)); + assert!((got - want).abs() < 0.5, "{what}: draws {got}, not {want}"); + } + } +} diff --git a/crates/engine/src/tests/ids_without_selection.rs b/crates/engine/src/tests/ids_without_selection.rs index b274e7956f..9a48655468 100644 --- a/crates/engine/src/tests/ids_without_selection.rs +++ b/crates/engine/src/tests/ids_without_selection.rs @@ -377,7 +377,7 @@ fn ids_cases(d: u64) -> Vec<(&'static str, &'static str, serde_json::Value, Unse ("addon.color.filter", "ids", json!({"effect": "addon.color.invert"}), Selected), ("addon.color.applyNearestSwatch", "ids", json!({}), Selected), ("edit.colors.overprintBlack", "ids", json!({}), Selected), - ("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1}))), + ("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1, "replaced": 1}))), ("layer.highlight", "ids", json!({}), Fails("missing ids")), ("layer.move", "ids", json!({ "target": d }), Fails("missing ids")), ("library.add", "ids", json!({"kind": "graphic"}), Selected), diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index e5cb1c8f63..c3bba6803b 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -167,6 +167,183 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() { assert_eq!(document_rows(&s), vec![g.0, c.0], "document.inspect lists the rows"); } +/// Run `layer.highlight` with `ids` and `mode` → (the rows it returned, the current layer), after +/// checking that the call counted one revision and left the rows it returned highlighted. +fn highlight_rows(s: &mut Session, ids: &[NodeId], mode: &str) -> (Vec, Option) { + let revision = s.doc().unwrap().revision; + let r = run(s, "layer.highlight", json!({"ids": ids.iter().map(|i| i.0).collect::>(), "mode": mode})); + let st = s.doc().unwrap(); + assert_eq!(st.revision, revision + 1, "{mode} {ids:?}"); + let rows: Vec = r["rows"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(rows, st.layer_rows, "{mode} {ids:?}"); + (rows, st.active_layer) +} + +/// `layer.highlight` keeps the rows in highlight order: `set` and `add` take a repeated id once, +/// `toggle` takes an id listed twice off and on again (or on and off, and its layer becomes the +/// current one), unknown ids and ids after the first 100,000 are dropped, rows highlighted twice +/// stay as they are on `add`, and `toggle` takes every copy off. +#[test] +fn highlighting_rows_keeps_their_order_with_repeated_unknown_and_excess_ids() { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + let unknown = NodeId(9999); + assert_eq!(highlight_rows(&mut s, &[a, g, a, unknown, c], "set"), (vec![a, g, c], Some(layer))); + assert_eq!(highlight_rows(&mut s, &[g, b, a, b], "add"), (vec![a, g, c, b], Some(sub))); + assert_eq!(highlight_rows(&mut s, &[c, c], "toggle"), (vec![a, g, b, c], Some(layer))); + // `sub` goes on and off again; it was the last row added, so its layer is the current one. + assert_eq!(highlight_rows(&mut s, &[sub, sub], "toggle"), (vec![a, g, b, c], Some(sub))); + assert_eq!(highlight_rows(&mut s, &[a, unknown], "toggle"), (vec![g, b, c], Some(layer))); + assert_eq!(highlight_rows(&mut s, &[], "add"), (vec![g, b, c], Some(layer))); + assert_eq!(highlight_rows(&mut s, &[], "toggle"), (vec![g, b, c], Some(layer))); + s.doc_mut().unwrap().active_layer = Some(sub); + assert_eq!(highlight_rows(&mut s, &[], "set"), (vec![], Some(sub)), "no rows: the current layer stays"); + let mut excess = vec![unknown; 100_000]; + excess.push(a); + assert_eq!(highlight_rows(&mut s, &excess, "set"), (vec![], Some(sub)), "only the first 100,000 ids count"); + s.doc_mut().unwrap().layer_rows = vec![a, a, g]; + assert_eq!(highlight_rows(&mut s, &[a, c], "add"), (vec![a, a, g, c], Some(layer))); + assert_eq!(highlight_rows(&mut s, &[a], "toggle"), (vec![g, c], Some(layer))); + // The same with more than 8 ids. + s.doc_mut().unwrap().layer_rows = vec![a, a, g]; + assert_eq!(highlight_rows(&mut s, &[a, c, c, c, c, c, c, c, c], "add"), (vec![a, a, g, c], Some(layer))); + s.doc_mut().unwrap().layer_rows = vec![a, a, g]; + assert_eq!(highlight_rows(&mut s, &[a, b, b, b, b, b, b, b, b], "toggle"), (vec![g], Some(sub)), "`b` goes on and off 4 times"); + assert_eq!(highlight_rows(&mut s, &[c, g, sub, g, sub, a, unknown, a, c, layer], "toggle"), (vec![g, layer], Some(layer))); + let revision = s.doc().unwrap().revision; + assert!(s.execute("layer.highlight", &json!({"ids": [b.0], "mode": "nope"})).is_err()); + let st = s.doc().unwrap(); + assert_eq!((st.revision, st.layer_rows.clone()), (revision, vec![g, layer]), "a bad mode changes nothing"); +} + +/// `layer.highlight`'s rule as a search of the highlighted rows for each id in `p`. The tests +/// compare the command with it. +fn highlight_by_search(st: &mut DocState, p: &Value) -> Value { + let mut ids: Vec = p["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + ids.truncate(crate::cmd::layer::MAX_ROWS); + let mode = p["mode"].as_str().unwrap_or("set"); + ids.retain(|id| st.doc.node(*id).is_some()); + let mut rows = st.highlighted_rows(); + if mode == "set" { + rows.clear(); + } + let mut last = None; + for id in ids { + if mode == "toggle" && rows.contains(&id) { + rows.retain(|r| *r != id); + } else if !rows.contains(&id) { + rows.push(id); + last = Some(id); + } + } + if let Some(layer) = last.or(rows.last().copied()).and_then(|id| st.doc.layer_containing(id)) { + st.active_layer = Some(layer); + } + st.layer_rows = rows; + st.revision += 1; + json!({ "rows": st.layer_rows.iter().map(|i| i.0).collect::>() }) +} + +/// Two sessions with `n` squares on a layer and a sublayer after them, and the squares' ids. +fn highlight_pair(n: usize) -> (Session, Session, Vec, NodeId) { + let make = || { + let mut s = super::large_edits::session(n, super::large_edits::square); + let sub = id(&run(&mut s, "layer.newSublayer", json!({"name": "Sub"}))); + (s, sub) + }; + let ((cmd, sub), (search, other)) = (make(), make()); + assert_eq!(sub, other); + let squares = super::large_edits::layer(&cmd, 0).into_iter().filter(|i| *i != sub).collect(); + (cmd, search, squares, sub) +} + +/// `p` for `layer.highlight` with `ids` and `mode`. +fn highlight_params(ids: impl IntoIterator, mode: &str) -> Value { + json!({"ids": ids.into_iter().map(|i| i.0).collect::>(), "mode": mode}) +} + +/// On 3,000 rows `layer.highlight` gives what [`highlight_by_search`] gives: the same rows in the +/// same order, the same current layer and the same returned rows, with repeated, unknown and +/// toggled ids. +#[test] +fn layer_highlight_matches_a_search_of_the_rows_for_each_id() { + let (mut cmd, mut search, sq, sub) = highlight_pair(3_000); + let unknown = NodeId(u64::MAX); + let steps = [ + highlight_params(sq[..2_000].iter().copied(), "set"), + highlight_params(sq[1_000..].iter().copied().chain([sub, sq[0]]), "add"), + highlight_params([sq[5], sq[5], sub, sq[2_999], unknown, sub, sub], "toggle"), + highlight_params(sq[500..520].iter().chain(&sq[510..515]).copied(), "toggle"), + highlight_params(sq.iter().rev().step_by(7).copied(), "add"), + highlight_params(sq.iter().step_by(3).copied().chain([sub]), "toggle"), + highlight_params(Vec::new(), "add"), + highlight_params(sq.iter().rev().step_by(2).chain(&sq[..10]).copied(), "set"), + highlight_params(Vec::new(), "set"), + ]; + for p in &steps { + let r = run(&mut cmd, "layer.highlight", p.clone()); + let expected = highlight_by_search(search.doc_mut().unwrap(), p); + let (a, b) = (cmd.doc().unwrap(), search.doc().unwrap()); + assert_eq!(r, expected, "{}", p["mode"]); + assert_eq!((&a.layer_rows, a.active_layer, a.revision), (&b.layer_rows, b.active_layer, b.revision), "{}", p["mode"]); + } +} + +/// Time `layer.highlight` against [`highlight_by_search`] on one layer of 20,000 paths: `set` of +/// all of them, `add` of 10,000 already highlighted and `toggle` of one, 7 runs each, both checked +/// to give the same rows and current layer. +/// Run with `cargo test --release -p vectorcraft-engine --lib layer_highlight_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn layer_highlight_timing() { + let (mut cmd, mut search, sq, _) = highlight_pair(20_000); + let steps = [ + ("set of 20,000", highlight_params(sq.iter().copied(), "set")), + ("add of 10,000", highlight_params(sq[5_000..15_000].iter().copied(), "add")), + ("toggle of 1", highlight_params([sq[10_000]], "toggle")), + ]; + let mut ms = vec![(Vec::new(), Vec::new()); steps.len()]; + for run_no in 0..7 { + for (i, (_, p)) in steps.iter().enumerate() { + let mut time_cmd = || { + let start = std::time::Instant::now(); + let r = cmd.execute("layer.highlight", p).unwrap(); + (start.elapsed().as_secs_f64() * 1000.0, r) + }; + let mut time_search = || { + let start = std::time::Instant::now(); + let r = highlight_by_search(search.doc_mut().unwrap(), p); + (start.elapsed().as_secs_f64() * 1000.0, r) + }; + // Alternate which goes first. + let ((tc, rc), (ts, rs)) = if run_no % 2 == 0 { + let c = time_cmd(); + (c, time_search()) + } else { + let s = time_search(); + (time_cmd(), s) + }; + assert_eq!(rc, rs); + let (a, b) = (cmd.doc().unwrap(), search.doc().unwrap()); + assert_eq!((&a.layer_rows, a.active_layer), (&b.layer_rows, b.active_layer)); + ms[i].0.push(ts); + ms[i].1.push(tc); + } + } + let median = |v: &[f64]| { + let mut v = v.to_vec(); + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + for ((name, _), (search_ms, cmd_ms)) in steps.iter().zip(&ms) { + println!( + "{name}: search {:.3} ms, command {:.3} ms (median of 7); search runs {search_ms:.3?}, command runs {cmd_ms:.3?}", + median(search_ms), + median(cmd_ms) + ); + } +} + fn document_rows(s: &Session) -> Vec { crate::inspect::document(s)["layerRows"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() } @@ -1102,6 +1279,43 @@ fn locate_object_highlights_its_row() { assert!(s.execute("layer.locate", &json!({})).is_err()); } +/// With several objects selected, Locate Object finds the frontmost one in the stacking order, +/// whatever order they were selected in; an `id` still wins. +#[test] +fn locate_object_finds_the_frontmost_selected_object() { + let mut s = session(); + let (_, sub, a, g, b, c) = tree(&mut s); + let top = id(&run(&mut s, "layer.new", json!({"top": true}))); + let d = rect(&mut s, 400.0); + let locate = |s: &mut Session, ids: &[NodeId]| { + run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::>()})); + assert_eq!(s.doc().unwrap().selection.objects.last(), ids.last(), "selected in this order"); + run(s, "layer.locate", json!({}))["id"].clone() + }; + // In one sublayer, the group in front of the rectangle selected last. + assert_eq!(locate(&mut s, &[g, a]), json!(g.0)); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g]); + // The sublayer sits in front of the art directly in its layer. + assert_eq!(locate(&mut s, &[a, c]), json!(a.0)); + // A higher layer wins over everything below it. + assert_eq!(locate(&mut s, &[d, b, c]), json!(d.0)); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![d]); + // A group and its member: the member paints after the group it is in. + assert_eq!(locate(&mut s, &[b, g]), json!(b.0)); + // Added one at a time, as by Shift-clicks. + run(&mut s, "select.set", json!({"ids": [d.0]})); + run(&mut s, "select.add", json!({"ids": [a.0]})); + assert_eq!(run(&mut s, "layer.locate", json!({}))["id"], d.0); + // An id still locates that object, behind the selection or not. + assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0}))["id"], c.0); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![c]); + // Locate Layer takes the layer of the frontmost selected object. + run(&mut s, "select.set", json!({"ids": [d.0, a.0]})); + assert_eq!(run(&mut s, "layer.locate", json!({"layersOnly": true})), json!({"id": top.0, "objectId": d.0, "ancestry": [top.0]})); + run(&mut s, "select.set", json!({"ids": [a.0, c.0]})); + assert_eq!(run(&mut s, "layer.locate", json!({"layersOnly": true}))["id"], sub.0); +} + /// Locate Layer (`layersOnly`, sent while Show Layers Only is on) highlights the innermost layer /// or sublayer holding the object, through any groups; a layer locates itself. #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 2656d8c4f8..32ea203053 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2377,7 +2377,8 @@ fn find_and_replace_leaves_type_on_a_locked_artboard() { /// Find and Replace that replaces each match with the text it is (`CAT` found in `cat`, ignoring /// case, and replaced by `cat`) records no undo step: the step to redo stays and the document stays -/// unmodified. It still replies with the count. A replacement that changes the text is one undo step. +/// unmodified. It still replies with the count, and with no match replaced. A replacement that +/// changes the text is one undo step. #[test] fn find_and_replace_that_changes_nothing_records_no_undo_step() { let mut s = session(); @@ -2385,9 +2386,9 @@ fn find_and_replace_that_changes_nothing_records_no_undo_step() { select_with_a_step_to_redo(&mut s, &[a]); let before = history(&s); assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved"); - assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2})); + assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2, "replaced": 0})); assert_eq!((history(&s), plain(&s, a)), (before, "cat cat".to_string())); - assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2})); + assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2, "replaced": 2})); assert_eq!((history(&s), plain(&s, a)), ((before.0 + 1, 0, true), "dog dog".to_string())); } @@ -2424,12 +2425,190 @@ fn find_next_cycles_through_text_objects() { let _ = text(&mut s, "banana"); let c = text(&mut s, "pineapple"); s.execute("select.none", &json!({})).unwrap(); - assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), a); + // From the top of the stacking order down, then round again. + assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), c); + assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a); assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), c); + // A selection that starts with a shape goes on after its first type object. + let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + sel(&mut s, &[shape, c]); assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a); assert!(s.execute("edit.findNext", &json!({"find": "zzz"})).unwrap()["id"].is_null()); } +/// The match `r` (an `edit.findNext` result) as (object, start, end, index, count). +fn found(r: &Value) -> (u64, u64, u64, u64, u64) { + let n = |k: &str| r[k].as_u64().unwrap_or_else(|| panic!("no `{k}` in {r}")); + (n("id"), n("start"), n("end"), n("index"), n("count")) +} + +/// Find Next steps through the matches one by one when each call is given the match before it: +/// the objects from the top of the stacking order down, each object's matches in reading order, +/// and round again after the last. Search Backwards visits them the other way. Each match is +/// returned with its bytes and its object is selected; nothing is recorded for undo. +#[test] +fn find_next_steps_through_the_matches_in_both_directions() { + let mut s = session(); + let bottom = text(&mut s, "cat éa cat"); + let _ = text(&mut s, "dog"); + let top = text(&mut s, "a cat"); + s.execute("select.none", &json!({})).unwrap(); + let before = history(&s); + let step = |s: &mut Session, from: &Value, backwards: bool| { + let from = if from.is_null() { Value::Null } else { json!({"id": from["id"], "start": from["start"], "end": from["end"]}) }; + s.execute("edit.findNext", &json!({"find": "cat", "from": from, "backwards": backwards})).unwrap() + }; + // "é" is two bytes, so the second match of the bottom object is at bytes 8..11. + let forward = [(top.0, 2, 5, 1, 3), (bottom.0, 0, 3, 2, 3), (bottom.0, 8, 11, 3, 3), (top.0, 2, 5, 1, 3)]; + let mut at = Value::Null; + for want in forward { + at = step(&mut s, &at, false); + assert_eq!((found(&at), selected(&s), at["selected"].clone()), (want, vec![NodeId(want.0)], json!(true))); + } + let backward = [(bottom.0, 8, 11, 3, 3), (bottom.0, 0, 3, 2, 3), (top.0, 2, 5, 1, 3), (bottom.0, 8, 11, 3, 3)]; + s.execute("select.none", &json!({})).unwrap(); + let mut at = Value::Null; + for want in backward { + at = step(&mut s, &at, true); + assert_eq!((found(&at), selected(&s)), (want, vec![NodeId(want.0)])); + } + assert_eq!(history(&s), before, "finding is no undo step"); + // A `from` in an object the search does not visit starts at the first match. + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": 999_999, "start": 0, "end": 0}})).unwrap(); + assert_eq!(found(&r), (top.0, 2, 5, 1, 3)); + // So does a null `from`, with a type object selected. + sel(&mut s, &[top]); + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": null})).unwrap(); + assert_eq!(found(&r), (top.0, 2, 5, 1, 3)); + // Nothing found: no match, and the selection stays. + let r = s.execute("edit.findNext", &json!({"find": "zebra"})).unwrap(); + assert_eq!((r, selected(&s)), (json!({"id": null, "count": 0}), vec![top])); +} + +/// Check Hidden Layers and Check Locked Layers: Find Next and Find and Replace leave the type of +/// a hidden layer and of a locked layer alone unless the switch for it is on. A match on such a +/// layer is returned without being selected. A hidden or locked object keeps its type out with +/// the switches on. +#[test] +fn find_and_replace_reach_hidden_and_locked_layers_only_when_asked() { + for (prop, switch, other) in [("visible", "hiddenLayers", "lockedLayers"), ("locked", "lockedLayers", "hiddenLayers")] { + let mut s = session(); + let open = text(&mut s, "cat one"); + let layer = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let closed = text(&mut s, "cat two"); + let object = text(&mut s, "cat three"); + let off = |id: NodeId| if prop == "visible" { json!({"id": id.0, "visible": false}) } else { json!({"id": id.0, "locked": true}) }; + s.execute("object.setProps", &off(object)).unwrap(); + s.execute("layer.setProps", &off(layer)).unwrap(); + sel(&mut s, &[open]); + // Without the switch, and with only the other one, the one reachable match is found. + for p in [json!({"find": "cat"}), json!({"find": "cat", other: true})] { + let r = s.execute("edit.findNext", &p).unwrap(); + assert_eq!(found(&r), (open.0, 0, 3, 1, 1), "{prop} {p}"); + } + // With it, the layer's type is searched (it is above, so it comes first) and not selected. + s.execute("select.none", &json!({})).unwrap(); + let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true})).unwrap(); + assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((closed.0, 0, 3, 1, 2), json!(false), vec![]), "{prop}"); + let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true, "from": {"id": closed.0, "start": 0, "end": 3}})).unwrap(); + assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((open.0, 0, 3, 2, 2), json!(true), vec![open]), "{prop}"); + // Replace All: the same reach. + let n = undo_len(&s); + assert_eq!( + s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", other: true})).unwrap(), + json!({"count": 1, "replaced": 1}), + "{prop}" + ); + assert_eq!((plain(&s, open), plain(&s, closed), plain(&s, object)), ("dog one".into(), "cat two".into(), "cat three".into()), "{prop}"); + assert_eq!( + s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", switch: true})).unwrap(), + json!({"count": 1, "replaced": 1}), + "{prop}" + ); + assert_eq!((plain(&s, closed), plain(&s, object), undo_len(&s)), ("dog two".into(), "cat three".into(), n + 2), "{prop}"); + } +} + +/// Replace changes one match, the bytes Find Next returned, as one undo step, and returns the +/// replacement's bytes to go on from. Bytes that are no match are refused, and a match that +/// already reads as the replacement is left with no undo step. +#[test] +fn replace_match_replaces_the_one_match_found() { + let mut s = session(); + let t = text(&mut s, "cat cat Cat"); + s.execute("select.none", &json!({})).unwrap(); + let first = s.execute("edit.findNext", &json!({"find": "cat"})).unwrap(); + assert_eq!(found(&first), (t.0, 0, 3, 1, 3)); + let n = undo_len(&s); + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "horse", "id": t.0, "start": 0, "end": 3})).unwrap(); + assert_eq!(r, json!({"id": t.0, "start": 0, "end": 5, "replaced": true})); + assert_eq!((plain(&s, t), undo_len(&s)), ("horse cat Cat".to_string(), n + 1)); + // Replace & Find: on from the replacement, so text put in is not searched again. + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "a cat", "id": t.0, "start": 6, "end": 9})).unwrap(); + let next = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": r["id"], "start": r["start"], "end": r["end"]}})).unwrap(); + assert_eq!((plain(&s, t), found(&next)), ("horse a cat Cat".to_string(), (t.0, 12, 15, 2, 2))); + // Match Case decides what a match is. + let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + s.execute("select.none", &json!({})).unwrap(); + let before = (history(&s), plain(&s, t)); + for (p, want) in [ + (json!({"find": "cat", "replace": "x", "matchCase": true, "id": t.0, "start": 12, "end": 15}), "at bytes 12..15 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 1, "end": 4}), "at bytes 1..4 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 4, "end": 1}), "at bytes 1..4 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 0}), "missing `end`"), + (json!({"find": "cat", "replace": "x", "start": 0, "end": 3}), "missing `id`"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": "0", "end": 3}), "`start` must be a whole number"), + (json!({"find": "", "replace": "x", "id": t.0, "start": 0, "end": 3}), "missing `find`"), + (json!({"find": "cat", "replace": 5, "id": t.0, "start": 8, "end": 11}), "`replace` must be a string"), + (json!({"find": "cat", "replace": "x", "id": shape.0, "start": 0, "end": 3}), "is not text"), + ] { + let r = s.execute("edit.replaceMatch", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}"); + assert_eq!((history(&s), plain(&s, t)), before, "{p}"); + } + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "x", "id": 999_999, "start": 0, "end": 3})); + assert!(matches!(r, Err(EngineError::NoNode(NodeId(999_999)))), "{r:?}"); + // A match that already reads as the replacement: nothing to undo. + let r = s.execute("edit.replaceMatch", &json!({"find": "CAT", "replace": "Cat", "id": t.0, "start": 12, "end": 15})).unwrap(); + assert_eq!((r, history(&s)), (json!({"id": t.0, "start": 12, "end": 15, "replaced": false}), before.0)); + // Find Next refuses a `from` that is not a match. + for (from, want) in [ + (json!(5), "missing `id`"), + (json!({"id": t.0, "start": 2}), "missing `end`"), + (json!({"id": "x", "start": 0, "end": 1}), "`id` must be a whole number"), + ] { + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": from})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{from}: {r:?}"); + } + for key in ["backwards", "hiddenLayers", "lockedLayers"] { + let r = s.execute("edit.findNext", &json!({"find": "cat", key: "yes"})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}"); + } + for key in ["hiddenLayers", "lockedLayers"] { + let r = s.execute("edit.findReplace", &json!({"find": "cat", key: 1})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}"); + } +} + +/// Ruby over text after a replaced match moves with the text, for Replace and for Replace All, as +/// it does when the text is typed. +#[test] +fn find_and_replace_moves_the_ruby_after_a_match() { + for all in [false, true] { + let mut s = session(); + let t = text(&mut s, "ab 漢字"); + sel(&mut s, &[t]); + s.execute("type.ruby", &json!({"text": "かんじ", "start": 3, "end": 9})).unwrap(); + if all { + s.execute("edit.findReplace", &json!({"find": "ab", "replace": "abcd"})).unwrap(); + } else { + s.execute("edit.replaceMatch", &json!({"find": "ab", "replace": "abcd", "id": t.0, "start": 0, "end": 2})).unwrap(); + } + let NodeKind::Text(tt) = &node(&s, t).kind else { panic!() }; + assert_eq!((tt.plain_text().as_str(), tt.ruby.first().map(|r| (r.start, r.end))), ("abcd 漢字", Some((5, 11))), "all: {all}"); + } +} + /// The Type menu's commands and Find and Replace and Find Next refuse a param of the wrong type, or /// `ids` that name no object, with an error naming the param, and leave the text, the selection and /// the undo history as they were, even when Insert Character is also given a source it would use diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 582543f7eb..777db5a381 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -326,9 +326,11 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() { let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap() }; + // Reopened existing links use native separators; missing links keep their stored path. + let red = dir.0.join("art").join("red.png").to_string_lossy().into_owned(); let person = report(&run(&mut s, "file.package", json!({}))); assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}"); - assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}"); + assert!(person.contains(&format!("{red} → Links/red.png")), "{person}"); assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}"); let in_root = dir.0.join("in"); @@ -339,16 +341,19 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() { assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}"); let base = dir.0.to_string_lossy().into_owned(); assert!(!text.contains(&base), "{text}"); + // Compare serialized JSON with the path encoded the same way, without its outer quotes. + let json_base = serde_json::to_string(&base).unwrap(); + let json_base = &json_base[1..json_base.len() - 1]; for key in ["missingLinks", "warnings", "files"] { - assert!(!client[key].to_string().contains(&base), "{key}: {client}"); + assert!(!client[key].to_string().contains(json_base), "{key}: {client}"); } // Document Info, whose report the package holds, gives no link either. for p in [json!({}), json!({"format": "text"})] { let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone())); - assert!(!info.to_string().contains(&base), "{p}: {info}"); + assert!(!info.to_string().contains(json_base), "{p}: {info}"); } let info = run(&mut s, "document.info", json!({"format": "text"})); - assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}"); + assert!(info["text"].as_str().unwrap().contains(&red), "the person's: {info}"); } /// A confined request packages no document that links, or places a native document or a PDF with diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index f20af794c4..dff77c1ce4 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1121,6 +1121,10 @@ fn path_commands_refuse_a_param_of_the_wrong_type() { s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.1 in", "joins": "Bevel"})).unwrap()); assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0])); + // A product with a unit, which the offset used to refuse: 0.05x2 in is 0.1 in. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.05x2 in", "joins": "Bevel"})).unwrap()); + assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0])); // Null switches keep Clean Up's defaults, which remove the stray point. let r = s.execute("object.path.cleanUp", &json!({"strayPoints": null, "unpaintedObjects": null, "emptyTextPaths": null})).unwrap(); assert_eq!(r["removed"], 1); diff --git a/crates/engine/src/tests/prefs_file.rs b/crates/engine/src/tests/prefs_file.rs index c2822ba937..bfe98b901b 100644 --- a/crates/engine/src/tests/prefs_file.rs +++ b/crates/engine/src/tests/prefs_file.rs @@ -176,3 +176,24 @@ fn a_file_over_the_limit_is_refused_before_it_is_parsed() { assert!(s.execute("prefs.import", &json!({"path": missing.to_string_lossy()})).is_err()); assert_eq!(s.prefs.to_json().to_string(), before); } + +/// Hold Shortcuts is off by default. The Hold Shortcut Delay takes 0.2 to 1.0 s and refuses other +/// values; a value from a settings file outside the range is brought inside it. +#[test] +fn hold_shortcut_preferences() { + let mut s = Session::new(); + assert!(!s.prefs.hold_shortcuts); + assert_eq!(s.prefs.key_hold_delay(), 0.35); + for ok in [0.2, 1.0] { + s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": ok})).unwrap(); + assert_eq!(s.prefs.key_hold_delay(), ok); + } + for bad in [0.1, 1.5] { + assert!(is_bad_params(s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": bad}))), "{bad}"); + } + s.execute("prefs.set", &json!({"key": "holdShortcuts", "value": true})).unwrap(); + assert!(s.prefs.hold_shortcuts); + let restored: Prefs = serde_json::from_value(json!({"keyHoldDelay": 5.0})).unwrap(); + assert_eq!(restored.key_hold_delay(), 1.0); + assert!(!restored.hold_shortcuts); +} diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index dae6a1729f..10c2edcc17 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -836,6 +836,49 @@ fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_p assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link"); } +/// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply` +/// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color +/// swatches in order. +#[test] +fn apply_with_a_group_keeps_its_gradient_swatch() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff"]})); + let fade = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()))); + s.edit("test", |d, _| { + let w = vectorcraft_color::Swatch { name: "Fade".into(), paint: fade.clone(), global: false, spot: false }; + d.swatch_groups.iter_mut().find(|g| g.name == "Brand").unwrap().swatches.insert(1, w); + Ok(()) + }) + .unwrap(); + let group = |s: &Session| -> Vec<(String, Option)> { + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.clone(); + g.iter().map(|w| (w.name.clone(), w.paint.color().map(|c| c.to_hex()))).collect() + }; + let names: Vec = group(&s).into_iter().map(|(n, _)| n).collect(); + rect(&mut s, json!("#ff0000")); + rect(&mut s, json!("#0000ff")); + select_all(&mut s); + // The rows' new colors go to the red and blue swatches; the gradient stays between them. + let map = json!([{"from": ["#ff0000"], "to": "#00ff00"}, {"from": ["#0000ff"], "to": "#ffff00"}]); + run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand"})); + let want = |a: &str, b: &str| vec![(names[0].clone(), Some(a.to_string())), (names[1].clone(), None), (names[2].clone(), Some(b.to_string()))]; + assert_eq!(group(&s), want("#00ff00", "#ffff00")); + assert_eq!(gradient_at(&s, 1), fade, "the gradient swatch keeps its paint"); + // `groupColors` counts the color swatches only: "keep" is the first, and the second color is + // the blue swatch's. + run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["keep", "#123456"]})); + assert_eq!(group(&s), want("#00ff00", "#123456")); + // A null removes the color swatch at its place and leaves the gradient. + run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": [null, "#123456"]})); + assert_eq!(group(&s), [(names[1].clone(), None), (names[2].clone(), Some("#123456".into()))]); + assert_eq!(gradient_at(&s, 0), fade); +} + +/// The paint of the swatch at place `i` of the group "Brand". +fn gradient_at(s: &Session, i: usize) -> vectorcraft_color::Paint { + s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches[i].paint.clone() +} + /// A row whose new color was removed keeps its art's colors: art in it linked to another swatch of /// the group, which the rewrite gives another color, loses the link instead of following it. #[test] diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 1ad659cfdd..cc6756c332 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -77,6 +77,31 @@ fn script_missing_include_reports_origin() { assert!(report["message"].as_str().unwrap().contains("include file not found: nope.jsxinc"), "{report}"); assert_eq!(report["log"], json!([]), "nothing ran before the include was read"); assert!(report.get("file").is_none(), "the line is the script's own"); + assert_eq!(report["messageOrigin"], "built-in"); + let _ = std::fs::remove_dir_all(base); +} + +/// An error in an included file keeps where its message came from: a value the file threw is the +/// script's own text, and an error the app raised for it, or for a file `$.evalFile` could not run, is not. +#[test] +fn script_include_errors_keep_their_message_origin() { + let base = folder("origin"); + write(&base.join("main/lib.jsxinc"), "var a = 1;\n throw new RangeError('invalid array length');"); + write(&base.join("main/native.jsxinc"), "var a = 1;\n new Array(-1);"); + for (text, message, origin) in [ + ("#include \"lib.jsxinc\"", "RangeError: invalid array length", "script"), + ("#include \"native.jsxinc\"", "RangeError: invalid array length", "built-in"), + ("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e; }", "RangeError: invalid array length", "built-in"), + ("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e.message; }", "invalid array length", "script"), + ] { + let report = failed(&base, text); + assert_eq!((report["message"].as_str(), report["messageOrigin"].as_str()), (Some(message), Some(origin)), "{text}: {report}"); + } + let report = failed(&base, "#include \"lib.jsxinc\""); + let file = report["file"].as_str().map(|f| Path::new(f).ends_with("lib.jsxinc")); + assert_eq!((file, report["line"].as_u64(), report["column"].as_u64()), (Some(true), Some(2), Some(3)), "{report}"); + let report = failed(&base, "$.evalFile('nope.jsx');"); + assert_eq!(report["messageOrigin"], "built-in", "{report}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 50828e855c..bf8154f9a7 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -170,6 +170,58 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(s.script_report().unwrap()["line"], 1); } +/// A failed run's report keeps its message and kind and says where the message came from: text the +/// script supplied, or one of the app's own errors. The status text and the console line read the +/// same either way, and only the app's own errors get advice about other applications' objects. +#[test] +fn failed_script_report_keeps_message_and_adds_origin() { + let mut s = two_docs(); + for (source, kind, message, origin) in [ + ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), + ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), + ("throw 'invalid array length';", "thrown", "invalid array length", "script"), + ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), + ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), + ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), + ("vc.run();", "thrown", "TypeError: vc.run: give a command id, as a string", "built-in"), + ] { + let e = run(&mut s, source).unwrap_err().to_string(); + let report = s.script_report().unwrap().clone(); + assert_eq!( + (report["kind"].as_str(), report["message"].as_str(), report["messageOrigin"].as_str()), + (Some(kind), Some(message), Some(origin)), + "{source}" + ); + let (line, column) = (&report["line"], &report["column"]); + let before = format!("t.js: line {line}, column {column}: "); + assert_eq!(e, format!("{before}{message} ({kind})"), "{source}"); + assert_eq!(s.script_failure_text().as_deref(), Some(e.as_str())); + let authored = s.script_authored_failure(); + assert_eq!(authored, (origin == "script").then(|| (before.clone(), message, format!(" ({kind})"))), "{source}"); + let console = s.execute("script.console", &json!({})).unwrap(); + let error = console["lines"].as_array().unwrap().iter().rev().find(|l| l["kind"] == "error").map(|l| l["text"].clone()); + assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); + } + // The app's own reference error names the `vc` object; the same text a script threw does not. + run(&mut s, "app.activeDocument;").unwrap_err(); + assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); + assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); + // An error in code `eval` compiled keeps where its message came from. + let e = run(&mut s, "eval(\"throw new Error('invalid array length')\");").unwrap_err().to_string(); + assert_eq!(e, "t.js: Error: invalid array length (thrown)"); + assert_eq!(s.script_authored_failure(), Some(("t.js: ".to_string(), "Error: invalid array length", " (thrown)".to_string()))); + // Syntax errors and limits are the app's own. + run(&mut s, "var = 1;").unwrap_err(); + assert_eq!((s.script_report().unwrap()["kind"].as_str(), s.script_authored_failure()), (Some("syntax"), None)); + s.execute("script.run", &json!({"source": "while (true) {}", "name": "t.js", "maxFuel": 100_000})).unwrap_err(); + assert_eq!((s.script_report().unwrap()["messageOrigin"].as_str(), s.script_authored_failure()), (Some("built-in"), None)); + // A run that completes has no failure to split. + run(&mut s, "throw 'x';").unwrap_err(); + run(&mut s, "1").unwrap(); + assert_eq!(s.script_authored_failure(), None); +} + /// An error raised where the run has no place for it, such as in code `eval` compiled, is named /// with the script and its kind alone, with one colon after the script's name. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 794cc7a2a3..65ea837527 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -188,8 +188,7 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - self.apply_actions(acts)?; + self.deactivate_tool(view)?; self.keep_tool_settings(); self.tool = self.make_tool(id); if let Some(selection) = text_selection { @@ -205,6 +204,18 @@ impl Session { Ok(()) } + /// Deactivate the tool and apply the actions it returns. In a batch, a Cancel is left out: the + /// batch settled the tool's drag when it began, and the open interaction holds the batch's + /// steps, which the batch keeps or rolls back as a whole. + pub(crate) fn deactivate_tool(&mut self, view: ViewInfo) -> Result<()> { + let mut acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); + if self.batch_stash.is_some() { + acts.retain(|a| !matches!(a, Action::Cancel)); + } + self.apply_actions(acts)?; + Ok(()) + } + /// The selection tools other than Direct Selection pick whole objects: with one of them chosen, /// an object selected in a symbol instance's art gives way to the instance. The revision /// changes with it, so panels that cache by revision show the instance. @@ -297,8 +308,7 @@ impl Session { // them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own. let mesh_points = (lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten(); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - let r = self.apply_actions(acts); + let r = self.deactivate_tool(view); self.keep_tool_settings(); self.tool = lender; if let Some(points) = mesh_points { @@ -311,7 +321,7 @@ impl Session { self.lent_selection = left; } self.after_command(None); - r.map(drop) + r } /// A fresh `id` tool with the options it keeps ([`settings`]): its last values, from this diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 4f49a25b03..b8114f705c 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1012,6 +1012,8 @@ fn structured_junk() { ("addon.pathtools.bridge", json!({"radius": 1e-308, "keepOriginals": "x"})), ("addon.pathtools.bridge", json!({"radius": 1000, "keepOriginals": true, "ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.bridge", json!({"radius": f64::MAX, "ids": [1, 1], "junk": [0]})), + ("addon.pathtools.bridge", json!({"gap": -1e308, "reach": f64::MAX, "ids": [0, 1, 2]})), + ("addon.pathtools.bridge", json!({"gap": 1000, "reach": 10000, "radius": null, "keepOriginals": true})), // Refused before anything is written: no format of that name, a time that is no time. ("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})), ("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})), diff --git a/crates/engine/tests/eraser_open_fill.rs b/crates/engine/tests/eraser_open_fill.rs new file mode 100644 index 0000000000..a0ab760660 --- /dev/null +++ b/crates/engine/tests/eraser_open_fill.rs @@ -0,0 +1,2062 @@ +//! Fill-only open-path Eraser regressions through the public engine and CPU renderer. +// Integration tests may unwrap and panic on failure (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{FillRule, PathData, Point}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + s +} + +fn path(s: &Session, id: NodeId) -> &PathData { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { path, .. } => path, + _ => panic!("the fixture is a path"), + } +} + +fn paths(s: &Session) -> Vec { + let mut paths = vec![]; + s.doc().unwrap().doc.walk(|node| { + if let NodeKind::Path { path, .. } = &node.kind { + paths.push(path.clone()); + } + }); + paths +} + +// The varied setting necessarily selects erase_varied, while a circular nib keeps the +// same deterministic swept area as the fixed tip. No random input or device is involved. +fn erase(s: &mut Session, mut params: Value, varied: bool) -> Value { + if varied { + params["angleMode"] = json!("pressure"); + params["angleVariation"] = json!(30); + params["roundness"] = json!(100); + } + s.execute("path.eraseRegion", ¶ms).unwrap() +} + +fn eraser_preserves_the_fill_of_an_open_rectangle_case(varied: bool) { + let samples = [(110.0, 125.0), (190.0, 125.0), (110.0, 175.0), (190.0, 175.0)]; + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + for closed in [true, false] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"closed": closed, "anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(path(&s, id).is_closed(), closed); + let before = render(&s); + for (x, y) in samples.into_iter().chain([(150.0, 150.0)]) { + assert_eq!(before.pixel(x as u32, y as u32), [0, 0, 0, 255], "closed={closed}: original fill at ({x}, {y})"); + } + + // The explicit command fixes the tip at 10 pt; its round ends are outside the rectangle. + erase(&mut s, json!({"points": [[50, 150], [250, 150]], "size": 10}), varied); + let remaining: Vec = paths(&s); + let filled = + |x, y| remaining.iter().any(|path| vectorcraft_geom::hit::fill_contains(&path.to_bezpath(), FillRule::NonZero, Point::new(x, y))); + let after = render(&s); + for (x, y) in samples { + assert!(filled(x, y), "closed={closed}: retained fill missing at ({x}, {y})"); + assert_eq!(after.pixel(x as u32, y as u32), [0, 0, 0, 255], "closed={closed}: retained pixel at ({x}, {y})"); + } + assert!(!filled(150.0, 150.0), "closed={closed}: eraser band still filled"); + assert_eq!(after.pixel(150, 150)[3], 0, "closed={closed}: erased pixel"); + let area: f64 = remaining.iter().map(|path| vectorcraft_pathops::area(path, FillRule::NonZero)).sum(); + assert!((area - 9000.0).abs() < 1.0, "closed={closed}: retained area {area}"); + } +} + +#[test] +fn eraser_preserves_the_fill_of_an_open_rectangle() { + eraser_preserves_the_fill_of_an_open_rectangle_case(false); +} + +#[test] +fn eraser_preserves_the_fill_of_an_open_rectangle_varied_tip() { + eraser_preserves_the_fill_of_an_open_rectangle_case(true); +} + +fn eraser_keeps_open_compound_holes_with_both_fill_rules_case(varied: bool) { + for rule in ["nonZero", "evenOdd"] { + let mut s = session(); + let outer = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 300, "y": 100}, {"x": 300, "y": 300}, {"x": 100, "y": 300} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let inner = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 150, "y": 150}, {"x": 150, "y": 250}, {"x": 250, "y": 250}, {"x": 250, "y": 150} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + for id in [outer, inner] { + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + } + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let members = match &s.doc().unwrap().doc.node(compound).unwrap().kind { + NodeKind::Compound { children, .. } => children, + other => panic!("expected compound path, got {other:?}"), + }; + assert!(members.iter().all(|member| !member.path_data().unwrap().is_closed()), "{rule}: both source contours remain open"); + let before = + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert!(before.pixel(120, 140)[3] > 240, "{rule}: ring fills before Eraser"); + assert_eq!(before.pixel(200, 200)[3], 0, "{rule}: the compound hole is empty before Eraser"); + let before_miss = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let miss_history = s.doc().unwrap().history.undo.len(); + let miss = erase(&mut s, json!({"points": [[200, 200]], "size": 10}), varied); + assert_eq!(miss["ids"], json!([]), "{rule}: a stroke wholly inside the hole misses"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_miss); + assert_eq!(s.doc().unwrap().history.undo.len(), miss_history, "{rule}: the hole miss adds no history"); + + erase(&mut s, json!({"points": [[80, 120], [320, 120]], "size": 10}), varied); + let after = + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert_eq!(after.pixel(120, 120)[3], 0, "{rule}: swept band is empty"); + assert!(after.pixel(120, 140)[3] > 240, "{rule}: retained ring is filled"); + assert_eq!(after.pixel(200, 200)[3], 0, "{rule}: compound hole remains empty"); + } +} + +#[test] +fn eraser_keeps_open_compound_holes_with_both_fill_rules() { + eraser_keeps_open_compound_holes_with_both_fill_rules_case(false); +} + +#[test] +fn eraser_keeps_open_compound_holes_with_both_fill_rules_varied_tip() { + eraser_keeps_open_compound_holes_with_both_fill_rules_case(true); +} + +fn eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie_case(varied: bool) { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}, {"x": 200, "y": 100} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!path(&s, id).is_closed(), "the bowtie is open"); + assert!(path(&s, id).subpaths.first().unwrap().signed_area().abs() < 1e-9, "the bowtie has zero signed area"); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before = render(&s); + let before_area: f64 = before.pixels.as_chunks::<4>().0.iter().map(|rgba| f64::from(rgba[3]) / 255.0).sum(); + assert!((before_area - 5000.0).abs() < 2.0, "the open bowtie fills both lobes: {before_area}"); + for y in [110, 140, 175] { + assert!(before.pixel(150, y)[3] > 240, "original lobe pixel y={y}"); + } + + erase(&mut s, json!({"points": [[50, 125], [250, 125]], "size": 10}), varied); + let after = render(&s); + let after_area: f64 = after.pixels.as_chunks::<4>().0.iter().map(|rgba| f64::from(rgba[3]) / 255.0).sum(); + assert!((after_area - 4500.0).abs() < 2.0, "only the 500 px² sweep strip is removed: {after_area}"); + assert!(after.pixel(150, 110)[3] > 240); + assert!(after.pixel(150, 140)[3] > 240); + assert!(after.pixel(150, 175)[3] > 240); + assert_eq!(after.pixel(150, 125)[3], 0, "the swept strip is empty"); + let area: f64 = paths(&s).iter().map(|path| vectorcraft_pathops::area(path, FillRule::NonZero)).sum(); + assert!((area - 4500.0).abs() < 1.0, "retained bowtie area {area}"); +} + +#[test] +fn eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie() { + eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie_case(false); +} + +#[test] +fn eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie_varied_tip() { + eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie_case(true); +} + +#[test] +fn eraser_keeps_painted_stroke_open_paths_on_the_outline_route() { + for varied in [false, true] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!path(&s, id).is_closed()); + let appearance = &s.doc().unwrap().doc.node(id).unwrap().appearance; + assert_eq!(appearance.stroke_width(), 4.0); + assert!(!appearance.stroke_paint().is_none()); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + let selection = s.doc().unwrap().selection.clone(); + let before_image = + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert_eq!(before_image.pixel(150, 150), [0, 0, 0, 255], "the interior really has visible fill"); + assert!(before_image.pixel(150, 100)[3] > 240, "the open path has painted visible stroke"); + // This sweep lies inside the fill, at least 30 pt from any painted outline. + // Fill-only scope must not extend to this painted-stroke path or wrap it. + let miss = erase(&mut s, json!({"points": [[130, 150], [170, 150]], "size": 10}), varied); + assert_eq!(miss["ids"], json!([]), "varied={varied}: the existing outline route misses"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before, "varied={varied}: no replacement or wrapper"); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert_eq!(s.doc().unwrap().selection, selection); + let after_image = + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert_eq!(after_image.pixels, before_image.pixels); + } +} + +// The Alt-drag marquee dispatches the same public Eraser command with `rect` instead of `points`. +fn marquee_rectangle(s: &mut Session, closed: bool, stroked: bool) -> NodeId { + let id = NodeId( + s.execute( + "path.create", + &json!({"closed": closed, "anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + if stroked { + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap(); + } else { + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + } + id +} + +#[test] +fn eraser_marquee_preserves_open_fill_like_closed_and_undo() { + for closed in [true, false] { + let mut s = session(); + let id = marquee_rectangle(&mut s, closed, false); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(path(&s, id).is_closed(), closed); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before_image = render(&s); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let retained = [(110, 125), (190, 125), (110, 175), (190, 175)]; + for (x, y) in retained.into_iter().chain([(150, 150)]) { + assert_eq!(before_image.pixel(x, y), [0, 0, 0, 255], "closed={closed}: original fill at ({x}, {y})"); + } + s.execute("path.eraseRegion", &json!({"rect": [50, 145, 200, 10]})).unwrap(); + let after_image = render(&s); + for (x, y) in retained { + assert_eq!(after_image.pixel(x, y), [0, 0, 0, 255], "closed={closed}: marquee lost retained fill at ({x}, {y})"); + } + assert_eq!(after_image.pixel(150, 150)[3], 0, "closed={closed}: marquee band is empty"); + let remaining = paths(&s); + let area: f64 = remaining.iter().map(|p| vectorcraft_pathops::area(p, FillRule::NonZero)).sum(); + assert!((area - 9000.0).abs() < 1.0, "closed={closed}: marquee retained area {area}"); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "one marquee is one edit"); + let after = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let after_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before, "closed={closed}: Undo restores the original document"); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after); + assert_eq!(s.doc().unwrap().selection, after_selection); + } +} + +#[test] +fn eraser_marquee_keeps_compound_holes_and_outline_controls() { + for rule in ["nonZero", "evenOdd"] { + let mut s = session(); + let mut ids = vec![]; + for anchors in [ + json!([{"x": 100, "y": 100}, {"x": 300, "y": 100}, {"x": 300, "y": 300}, {"x": 100, "y": 300}]), + json!([{"x": 150, "y": 150}, {"x": 150, "y": 250}, {"x": 250, "y": 250}, {"x": 250, "y": 150}]), + ] { + let id = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + ids.push(id); + } + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let members = match &s.doc().unwrap().doc.node(compound).unwrap().kind { + NodeKind::Compound { children, .. } => children, + other => panic!("expected compound, got {other:?}"), + }; + assert!(members.iter().all(|n| !n.path_data().unwrap().is_closed())); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before_image = render(&s); + assert!(before_image.pixel(120, 120)[3] > 240, "{rule}: original ring is filled"); + assert_eq!(before_image.pixel(200, 200)[3], 0, "{rule}: original hole is empty"); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = s.execute("path.eraseRegion", &json!({"rect": [180, 180, 40, 40]})).unwrap(); + assert_eq!(miss["ids"], json!([]), "{rule}: a marquee wholly inside the hole misses"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = s.execute("path.eraseRegion", &json!({"rect": [80, 115, 240, 10]})).unwrap(); + assert!(!result["ids"].as_array().unwrap().is_empty()); + for id in result["ids"].as_array().unwrap() { + assert!( + matches!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind, NodeKind::Compound { .. }), + "{rule}: no wrapper replaces the compound pieces" + ); + } + let after_image = render(&s); + assert_eq!(after_image.pixel(120, 120)[3], 0, "{rule}: marquee band is empty"); + assert!(after_image.pixel(120, 140)[3] > 240, "{rule}: ring outside the marquee remains filled"); + assert_eq!(after_image.pixel(200, 200)[3], 0, "{rule}: compound hole stays empty"); + let area: f64 = after_image.pixels.as_chunks::<4>().0.iter().map(|rgba| f64::from(rgba[3]) / 255.0).sum(); + assert!((area - 28000.0).abs() < 2.0, "{rule}: marquee removes only its 2000 px² strip: {area}"); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + } + + // Filled AND painted-stroke open art keeps the existing outline route, so an interior + // marquee that touches none of its three painted edges is a genuine no-op. + let mut s = session(); + let id = marquee_rectangle(&mut s, false, true); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = s.execute("path.eraseRegion", &json!({"rect": [130, 145, 40, 10]})).unwrap(); + assert_eq!(miss["ids"], json!([])); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + + // Knife's target collection must not inherit the Eraser-only open-fill area extension. + let mut s = session(); + let id = marquee_rectangle(&mut s, false, false); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = s.execute("path.knife", &json!({"points": [[50, 150], [250, 150]]})).unwrap(); + assert_eq!(miss["ids"], json!([])); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); +} + +// A mask is a role of one first child, not a collection of ordinary sibling pieces. +struct ClipMaskFixture { + group: NodeId, + mask: NodeId, + art: NodeId, + compound: bool, + rule: FillRule, + appearance: Value, + art_json: Value, +} + +fn blue_clip_art(s: &mut Session) -> NodeId { + let art = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 300, "height": 300})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [art.0], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [art.0], "none": true})).unwrap(); + art +} + +fn painted_clip(s: &mut Session, art: NodeId, mask: NodeId, compound: bool) -> ClipMaskFixture { + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + let group = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert!(s.doc().unwrap().doc.node(mask).unwrap().appearance.fill_paint().is_none(), "Make clears the clipping path's paint"); + // The reported area route requires visible fill on the mask AFTER Make, which clears it. + s.execute("paint.setFill", &json!({"ids": [mask.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [mask.0], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [mask.0]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![mask], "only the mask is an Eraser target"); + let node = s.doc().unwrap().doc.node(mask).unwrap(); + assert!(!node.appearance.fill_paint().is_none(), "the restored visible fill admits the area route"); + assert!(node.appearance.stroke_paint().is_none(), "no painted stroke admits an outline fallback"); + let rule = match &node.kind { + NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule, + other => panic!("expected a path or compound mask, got {other:?}"), + }; + let fixture = ClipMaskFixture { + group, + mask, + art, + compound, + rule, + appearance: serde_json::to_value(&node.appearance).unwrap(), + art_json: serde_json::to_value(s.doc().unwrap().doc.node(art).unwrap()).unwrap(), + }; + assert_clip_identity(s, &fixture); + fixture +} + +fn assert_clip_identity(s: &Session, c: &ClipMaskFixture) { + let d = &s.doc().unwrap().doc; + let children = match &d.node(c.group).unwrap().kind { + NodeKind::Group { children, clip: true } => children, + other => panic!("expected the original clip group, got {other:?}"), + }; + assert_eq!(children.iter().map(|n| n.id).collect::>(), [c.mask, c.art], "the one mask stays first; no painted siblings or promoted art"); + let mask = d.node(c.mask).unwrap(); + let rule = match (&mask.kind, c.compound) { + (NodeKind::Path { rule, clipping: true, .. }, false) | (NodeKind::Compound { rule, .. }, true) => *rule, + (other, _) => panic!("the original mask kind/role changed: {other:?}"), + }; + assert_eq!(rule, c.rule); + assert_eq!(serde_json::to_value(&mask.appearance).unwrap(), c.appearance); + assert_eq!(serde_json::to_value(d.node(c.art).unwrap()).unwrap(), c.art_json, "the clipped art itself is untouched"); +} + +fn assert_clip_pixels(s: &Session, blue: &[(u32, u32)], clear: &[(u32, u32)]) { + let image = vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + for &(x, y) in blue { + assert_eq!(image.pixel(x, y), [0, 0, 255, 255], "clipped blue art at ({x}, {y}), not a painted mask sibling"); + } + for &(x, y) in clear { + assert_eq!(image.pixel(x, y)[3], 0, "transparent clip region at ({x}, {y})"); + } +} + +fn clip_eraser(s: &mut Session, mode: &str, full: bool) -> Value { + if mode == "rect" { + let rect = if full { json!([50, 50, 300, 300]) } else { json!([50, 145, 200, 10]) }; + s.execute("path.eraseRegion", &json!({"rect": rect})).unwrap() + } else { + assert!(matches!(mode, "fixed" | "varied")); + let params = if full { json!({"points": [[150, 150]], "size": 300}) } else { json!({"points": [[50, 150], [250, 150]], "size": 10}) }; + erase(s, params, mode == "varied") + } +} + +fn fully_erase_clip_and_restore(s: &mut Session, c: &ClipMaskFixture, mode: &str) { + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + clip_eraser(s, mode, true); + let image = vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert!(image.pixels.as_chunks::<4>().0.iter().all(|pixel| pixel[3] == 0), "empty geometry must hide all clipped art, not promote it"); + assert_clip_identity(s, c); + match &s.doc().unwrap().doc.node(c.mask).unwrap().kind { + NodeKind::Path { path, .. } => assert!(path.is_empty()), + NodeKind::Compound { children, .. } => assert!(children.is_empty()), + other => panic!("empty mask retains its kind: {other:?}"), + } + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let empty = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let empty_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), empty); + assert_eq!(s.doc().unwrap().selection, empty_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + assert_clip_identity(s, c); +} + +#[test] +fn eraser_clipping_split_and_empty_masks_keep_their_single_role() { + for closed in [false, true] { + for mode in ["fixed", "varied", "rect"] { + let mut s = session(); + let art = blue_clip_art(&mut s); + let mask = marquee_rectangle(&mut s, closed, false); + let c = painted_clip(&mut s, art, mask, false); + assert_eq!(path(&s, mask).is_closed(), closed, "the original mask's open/closed state is real"); + assert_clip_pixels(&s, &[(110, 125), (190, 125), (110, 175), (190, 175), (150, 150)], &[(90, 150)]); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + clip_eraser(&mut s, mode, false); + assert_clip_pixels(&s, &[(110, 125), (190, 125), (110, 175), (190, 175)], &[(150, 150), (90, 150)]); + assert_clip_identity(&s, &c); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "closed={closed}, mode={mode}: one erase edit"); + let split = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let split_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), split); + assert_eq!(s.doc().unwrap().selection, split_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + fully_erase_clip_and_restore(&mut s, &c, mode); + } + } +} + +#[test] +fn eraser_clipping_compound_holes_and_empty_masks_keep_their_rule() { + for rule in ["nonZero", "evenOdd"] { + let mut s = session(); + let art = blue_clip_art(&mut s); + let mut ids = vec![]; + for anchors in [ + json!([{"x": 100, "y": 100}, {"x": 300, "y": 100}, {"x": 300, "y": 300}, {"x": 100, "y": 300}]), + json!([{"x": 150, "y": 150}, {"x": 150, "y": 250}, {"x": 250, "y": 250}, {"x": 250, "y": 150}]), + ] { + let id = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + ids.push(id); + } + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let mask = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + let c = painted_clip(&mut s, art, mask, true); + assert_eq!(c.rule, if rule == "evenOdd" { FillRule::EvenOdd } else { FillRule::NonZero }); + let members = match &s.doc().unwrap().doc.node(mask).unwrap().kind { + NodeKind::Compound { children, .. } => children, + other => panic!("expected compound, got {other:?}"), + }; + assert!(members.iter().all(|member| !member.path_data().unwrap().is_closed()), "the source contours are open"); + assert_clip_pixels(&s, &[(120, 110), (120, 120), (120, 140)], &[(200, 200), (90, 110)]); + // First witness the independent zero-mask promotion defect in actual pixels. + let original = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let original_selection = s.doc().unwrap().selection.clone(); + let original_history = s.doc().unwrap().history.undo.len(); + fully_erase_clip_and_restore(&mut s, &c, "rect"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), original); + assert_eq!(s.doc().unwrap().selection, original_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), original_history); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + s.execute("path.eraseRegion", &json!({"rect": [80, 115, 240, 10]})).unwrap(); + assert_clip_identity(&s, &c); + assert_clip_pixels(&s, &[(120, 110), (120, 140)], &[(120, 120), (200, 200), (90, 110)]); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let split = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let split_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), split); + assert_eq!(s.doc().unwrap().selection, split_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + // Member IDs may be rebuilt by set_geometry; only the compound mask's own role is stable. + } +} + +#[test] +fn eraser_clipping_path_eraser_keeps_mask_but_removes_ordinary_art() { + let mut s = session(); + let art = blue_clip_art(&mut s); + let mask = marquee_rectangle(&mut s, false, false); + let c = painted_clip(&mut s, art, mask, false); + assert!(!path(&s, mask).is_closed()); + assert_clip_pixels(&s, &[(190, 110), (190, 150), (190, 190)], &[(90, 150)]); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + s.execute("path.eraseSegments", &json!({"points": [[50, 150], [250, 150]], "width": 10})).unwrap(); + // The two open outline pieces close as triangles for clipping, not as an area subtraction. + assert_clip_pixels(&s, &[(190, 110), (190, 190)], &[(190, 150), (90, 150)]); + assert_clip_identity(&s, &c); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let split = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let split_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), split); + assert_eq!(s.doc().unwrap().selection, split_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + + // The same shared apply_plan must still REMOVE wholly erased ordinary art. + let mut s = session(); + let ordinary = marquee_rectangle(&mut s, false, false); + s.execute("select.set", &json!({"ids": [ordinary.0]})).unwrap(); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + s.execute("path.eraseSegments", &json!({"points": [[50, 150], [250, 150]], "width": 300})).unwrap(); + assert!(s.doc().unwrap().doc.node(ordinary).is_none(), "ordinary art does not retain an empty mask node"); + assert!(s.doc().unwrap().selection.is_empty()); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(ordinary).is_none()); + assert!(s.doc().unwrap().selection.is_empty()); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); +} + +// Bounds-fitted fill gradients are page-space paints, not Along-stroke gradients. +fn eraser_gradient_fill(s: &mut Session, id: NodeId, placed: bool) -> Value { + let mut gradient = json!({"kind": "linear", "angle": 90, "dither": false, "stops": [ + {"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"} + ]}); + if placed { + gradient["start"] = json!([150, 200]); + gradient["end"] = json!([150, 100]); + } + s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": gradient})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let vectorcraft_doc::color::Paint::Gradient(g) = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() else { + panic!("the public paint command must install a gradient fill"); + }; + assert_eq!(g.geom.is_some(), placed, "the fixture distinguishes fitted and explicitly placed gradients"); + assert!(!g.gradient.dither, "exact retained-pixel comparisons do not use noise"); + serde_json::to_value(g.geom).unwrap() +} + +fn eraser_gradient_image(s: &Session) -> vectorcraft_render::Rendered { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) +} + +fn eraser_gradient_region(s: &mut Session, mode: &str, trim: bool, miss: bool) -> Value { + if mode == "rect" { + let rect = if miss { + json!([10, 10, 10, 10]) + } else if trim { + json!([50, 90, 200, 20]) + } else { + json!([50, 145, 200, 10]) + }; + s.execute("path.eraseRegion", &json!({"rect": rect})).unwrap() + } else { + assert!(matches!(mode, "fixed" | "varied")); + let params = if miss { + json!({"points": [[20, 20]], "size": 10}) + } else if trim { + json!({"points": [[50, 100], [250, 100]], "size": 20}) + } else { + json!({"points": [[50, 150], [250, 150]], "size": 10}) + }; + erase(s, params, mode == "varied") + } +} + +fn eraser_gradient_rectangle_case(closed: bool, mode: &str, trim: bool, placed: bool) { + let mut s = session(); + let id = marquee_rectangle(&mut s, closed, false); + let placed_geom = eraser_gradient_fill(&mut s, id, placed); + assert_eq!(path(&s, id).is_closed(), closed); + let before_image = eraser_gradient_image(&s); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + for y in [125, 175] { + assert_eq!(before_image.pixel(150, y)[3], 255, "the retained sample is inside the original fill"); + } + assert_ne!(before_image.pixel(150, 125), before_image.pixel(150, 175), "the original ramp varies vertically"); + let erased_y = if trim { 105 } else { 150 }; + assert_eq!(before_image.pixel(150, erased_y)[3], 255); + + let miss = eraser_gradient_region(&mut s, mode, trim, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "a miss must not pin or replace the document"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + + let result = eraser_gradient_region(&mut s, mode, trim, false); + let ids = result["ids"].as_array().unwrap(); + assert_eq!(ids.len(), if trim { 1 } else { 2 }, "closed={closed}, mode={mode}, trim={trim}: actual piece count"); + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(150, erased_y)[3], 0, "the erase operation really removes the intended band"); + for y in [125, 175] { + assert_eq!( + after_image.pixel(150, y), + before_image.pixel(150, y), + "closed={closed}, mode={mode}, trim={trim}, placed={placed}: retained gradient color at (150, {y})" + ); + } + if placed { + for id in ids { + let node = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap(); + let vectorcraft_doc::color::Paint::Gradient(g) = node.appearance.fill_paint() else { panic!("the placed fill remains a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), placed_geom, "an explicit vector is not refitted"); + } + } + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "one erase is one edit"); + let after = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let after_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after); + assert_eq!(s.doc().unwrap().selection, after_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + assert_eq!(eraser_gradient_image(&s).pixels, after_image.pixels, "Redo restores the exact rendered result"); +} + +#[test] +fn eraser_gradient_retains_page_colors_for_split_trim_and_placed_fill() { + // A legal already-placed vector is the positive control for the shared pinning seam. + eraser_gradient_rectangle_case(false, "fixed", false, true); + for closed in [false, true] { + for mode in ["fixed", "varied", "rect"] { + for trim in [false, true] { + eraser_gradient_rectangle_case(closed, mode, trim, false); + } + } + } +} + +fn eraser_gradient_compound_fixture(s: &mut Session, rule: &str) -> (NodeId, NodeId, NodeId) { + let mut ids = vec![]; + for anchors in [ + json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]), + json!([{"x": 140, "y": 140}, {"x": 140, "y": 160}, {"x": 160, "y": 160}, {"x": 160, "y": 140}]), + ] { + let id = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + ids.push(id); + } + let outer = NodeId(*ids.first().unwrap()); + let inner = NodeId(*ids.get(1).unwrap()); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + eraser_gradient_fill(s, compound, false); + let owner = s.doc().unwrap().doc.node(compound).unwrap(); + let members = match &owner.kind { + NodeKind::Compound { children, .. } => children, + other => panic!("expected a compound, got {other:?}"), + }; + assert_eq!(members.len(), 2); + for member in members { + assert!(!member.path_data().unwrap().is_closed(), "the compound's source contours are genuinely open"); + assert!(member.appearance.fill_paint().is_none() && member.appearance.stroke_paint().is_none(), "the parent alone owns the paint"); + } + let bounds = owner.geometric_bounds().unwrap(); + assert_eq!(bounds, vectorcraft_geom::Rect::new(100.0, 100.0, 200.0, 200.0)); + (outer, inner, compound) +} + +fn eraser_gradient_compound_case(outline: bool, rule: &str) { + let mut s = session(); + let (outer, inner, compound) = eraser_gradient_compound_fixture(&mut s, rule); + let before_image = eraser_gradient_image(&s); + let retained = if outline { vec![(190, 175)] } else { vec![(150, 125), (150, 175)] }; + for &(x, y) in &retained { + assert_eq!(before_image.pixel(x, y)[3], 255, "{rule}: retained source interior"); + } + assert_ne!(before_image.pixel(190, 125), before_image.pixel(190, 175), "the parent paint is a nonconstant vertical ramp"); + assert_eq!(before_image.pixel(155, 155)[3], 0, "the source hole is empty"); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let inner_before = serde_json::to_value(s.doc().unwrap().doc.node(inner).unwrap()).unwrap(); + let miss = if outline { + s.execute("path.eraseSegments", &json!({"points": [[20, 20]], "width": 20})).unwrap() + } else { + s.execute("path.eraseRegion", &json!({"rect": [145, 145, 10, 10]})).unwrap() + }; + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "{rule}: no-op must not pin the owner"); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert_eq!(s.doc().unwrap().selection, selection); + + if outline { + // Path Eraser plans the outer leaf, but its Compound parent supplies the gradient. + s.execute("path.eraseSegments", &json!({"points": [[50, 100], [250, 100]], "width": 20})).unwrap(); + let after_bounds = s.doc().unwrap().doc.node(compound).unwrap().geometric_bounds().unwrap(); + assert!((after_bounds.y0 - 110.0).abs() < 1e-5, "the edited extremal outline shrinks the parent fit: {after_bounds:?}"); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.node(inner).unwrap()).unwrap(), inner_before, "the inner member itself was not edited"); + let hole = Point::new(155.0, 155.0); + assert!( + vectorcraft_geom::hit::fill_contains(&path(&s, outer).to_bezpath(), FillRule::NonZero, hole), + "the sample remains inside the outer fill" + ); + assert!( + vectorcraft_geom::hit::fill_contains(&path(&s, inner).to_bezpath(), FillRule::NonZero, hole), + "the unchanged inner contour still makes a hole there" + ); + } else { + s.execute("path.eraseRegion", &json!({"rect": [50, 145, 200, 10]})).unwrap(); + } + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(155, 155)[3], 0, "{rule}: the un-erased part of the hole stays empty"); + if !outline { + assert_eq!(after_image.pixel(190, 150)[3], 0, "the marquee actually removes filled art across the ring"); + assert_eq!(after_image.pixel(150, 142)[3], 0, "the hole above the erased band remains empty"); + } + for &(x, y) in &retained { + assert_eq!( + after_image.pixel(x, y), + before_image.pixel(x, y), + "{rule}, outline={outline}: parent-owned gradient must keep its original color at ({x}, {y})" + ); + } + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let after = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let after_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after); + assert_eq!(s.doc().unwrap().selection, after_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + assert_eq!(eraser_gradient_image(&s).pixels, after_image.pixels); +} + +#[test] +fn eraser_gradient_compound_owner_keeps_page_colors_and_holes() { + for outline in [true, false] { + for rule in ["nonZero", "evenOdd"] { + eraser_gradient_compound_case(outline, rule); + } + } +} + +fn eraser_container_gradient_fixture(s: &mut Session, placed: bool, nested: bool) -> (NodeId, NodeId, NodeId, Value) { + let mut ids = vec![]; + for anchors in [ + json!([{"x": 100, "y": 100}, {"x": 150, "y": 100}, {"x": 150, "y": 140}, {"x": 100, "y": 140}]), + json!([{"x": 170, "y": 160}, {"x": 220, "y": 160}, {"x": 220, "y": 200}, {"x": 170, "y": 200}]), + ] { + let id = s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + ids.push(id); + } + let edited = NodeId(ids[0]); + let sibling = NodeId(ids[1]); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let inner = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let owner = if nested { NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) } else { inner }; + s.execute("appearance.addFill", &json!({"ids": [owner.0], "target": "object"})).unwrap(); + let mut gradient = json!({"kind": "linear", "angle": 90, "dither": false, "stops": [ + {"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"} + ]}); + if placed { + gradient["start"] = json!([160, 200]); + gradient["end"] = json!([160, 100]); + } + s.execute("appearance.setItem", &json!({"ids": [owner.0], "target": "object", "index": 0, "gradient": gradient})).unwrap(); + let d = &s.doc().unwrap().doc; + let n = d.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert_eq!(n.appearance.items.len(), 1, "the Group owns one fill row"); + assert_eq!(n.appearance.contents_at(), 0, "the own fill paints above the children's black fills"); + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the Group itself owns the gradient") }; + assert_eq!(g.geom.is_some(), placed); + assert!(!g.gradient.dither); + let geom = serde_json::to_value(g.geom).unwrap(); + assert_eq!(n.geometric_bounds().unwrap(), vectorcraft_geom::Rect::new(100.0, 100.0, 220.0, 200.0)); + for id in [edited, sibling] { + assert!(!d.node(id).unwrap().appearance.has_unplaced_gradient(), "the gradient is not on a leaf"); + } + assert_eq!(d.parent_of(edited), Some(inner)); + if nested { + assert_eq!(d.parent_of(inner), Some(owner)); + assert!(d.node(inner).unwrap().appearance.items.is_empty(), "the intervening Group has no own paint"); + } + s.execute("select.set", &json!({"ids": [edited.0]})).unwrap(); + (edited, sibling, owner, geom) +} + +fn eraser_container_gradient_restore(s: &mut Session, before: &Value, selection: &vectorcraft_doc::Selection, history: usize) { + let after = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let after_selection = s.doc().unwrap().selection.clone(); + let after_pixels = eraser_gradient_image(s).pixels; + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "one erase remains one edit"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), *before); + assert_eq!(&s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after); + assert_eq!(s.doc().unwrap().selection, after_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + assert_eq!(eraser_gradient_image(s).pixels, after_pixels); +} + +fn eraser_container_gradient_case(placed: bool, nested: bool) { + let mut s = session(); + let (edited, sibling, owner, geom) = eraser_container_gradient_fixture(&mut s, placed, nested); + let before_image = eraser_gradient_image(&s); + assert_eq!(before_image.pixel(125, 105)[3], 255, "the extremal child really paints the erase region"); + assert_eq!(before_image.pixel(190, 175)[3], 255); + assert_ne!(before_image.pixel(190, 175), before_image.pixel(190, 185), "the owner's paint varies on the untouched sibling"); + assert_ne!(before_image.pixel(190, 175), [0, 0, 0, 255], "the Group's top paint actually covers the black child"); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let sibling_before = serde_json::to_value(before.node(sibling).unwrap()).unwrap(); + let ancestry = before.ancestry(edited).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = eraser_gradient_region(&mut s, "rect", true, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "a miss must not replace any ancestor"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = eraser_gradient_region(&mut s, "rect", true, false); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "trim keeps one piece, not a split"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry, "the child and every original container retain their roles"); + assert_eq!(serde_json::to_value(d.node(sibling).unwrap()).unwrap(), sibling_before, "the sibling itself was not edited"); + let n = d.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert!((n.geometric_bounds().unwrap().y0 - 110.0).abs() < 1e-5, "the owner's original minimum y really shrinks"); + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(125, 105)[3], 0, "the intended band is erased through the Group's paint"); + assert_eq!( + after_image.pixel(190, 175), + before_image.pixel(190, 175), + "placed={placed}, nested={nested}: erasing one child must not recolor its untouched sibling" + ); + if placed { + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the own fill stays a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), geom, "an explicitly placed owner is not refitted"); + } + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); +} + +#[test] +fn eraser_container_gradient_keeps_untouched_sibling_colors() { + // Positive control runs before the unchanged-product fitted-paint failure. + eraser_container_gradient_case(true, false); + eraser_container_gradient_case(false, false); + eraser_container_gradient_case(false, true); +} + +fn eraser_container_effect_gradient_case(group: bool, placed: bool) { + let mut s = session(); + let (edited, owner, geom) = if group { + let (edited, _, owner, geom) = eraser_container_gradient_fixture(&mut s, placed, false); + (edited, owner, geom) + } else { + let id = marquee_rectangle(&mut s, true, false); + let geom = eraser_gradient_fill(&mut s, id, placed); + (id, id, geom) + }; + s.execute( + "effect.apply", + &json!({ + "ids": [owner.0], "target": "object", "item": null, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"} + }), + ) + .unwrap(); + let d = &s.doc().unwrap().doc; + let n = d.node(owner).unwrap(); + assert_eq!(n.appearance.effects.len(), 1); + let effect = &n.appearance.effects[0]; + assert_eq!(effect.id, "path.offsetPath"); + assert!(effect.visible); + assert_eq!(effect.params["offset"].as_f64(), Some(10.0)); + assert_eq!(effect.params["joins"], json!("round")); + let effect_before = serde_json::to_value(&n.appearance.effects).unwrap(); + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the effect owner really owns the gradient") }; + assert_eq!(g.geom.is_some(), placed); + assert!(!g.gradient.dither); + assert_eq!(g.gradient.stops.len(), 2); + assert_ne!(g.gradient.stops[0].color, g.gradient.stops[1].color, "the own paint is a real nonconstant ramp before rendering"); + let original_bounds = n.geometric_bounds().unwrap(); + assert_eq!((original_bounds.y0, original_bounds.y1), (100.0, 200.0)); + let before_image = eraser_gradient_image(&s); + assert_eq!(before_image.pixel(125, 105)[3], 255); + assert_eq!(before_image.pixel(190, 175)[3], 255); + assert_eq!(before_image.pixel(190, 185)[3], 255); + assert_ne!(before_image.pixel(190, 175), before_image.pixel(190, 185), "the rendered own gradient is nonconstant"); + assert_eq!(before_image.pixel(190, 205)[3], 255, "the live positive offset paints beyond the source's y=200 bounds"); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let ancestry = before.ancestry(edited).unwrap(); + let miss = s.execute("path.eraseRegion", &json!({"rect": [10, 10, 10, 10]})).unwrap(); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + + // Remove 30 pt of source height: the remaining +10 pt live offset cannot + // repaint the cleared (125,105) pixel. The offset itself remains live. + let result = s.execute("path.eraseRegion", &json!({"rect": [50, 80, 200, 50]})).unwrap(); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "this is a one-piece extremal trim"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry); + let n = d.node(owner).unwrap(); + assert!((n.geometric_bounds().unwrap().y0 - 130.0).abs() < 1e-5, "the original owner bounds really shrink"); + assert_eq!(serde_json::to_value(&n.appearance.effects).unwrap(), effect_before, "the edit must not flatten or remove the live effect"); + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(125, 105)[3], 0, "the +10 offset cannot repaint this deliberately deep erased band"); + assert_eq!( + after_image.pixel(190, 175), + before_image.pixel(190, 175), + "group={group}, placed={placed}: freezing the raw Node box must not recolor retained effected art" + ); + if placed { + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the placed fill remains a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), geom); + } + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); +} + +#[test] +fn eraser_container_gradient_keeps_evaluated_offset_fit() { + // Establish ordinary legal placement through the SAME live offset first. + eraser_container_effect_gradient_case(true, true); + eraser_container_effect_gradient_case(false, true); + eraser_container_effect_gradient_case(true, false); + eraser_container_effect_gradient_case(false, false); +} + +fn eraser_placement_ramp(placed: bool, bottom: f64, top: f64) -> Value { + let mut gradient = json!({"kind": "linear", "angle": 90, "dither": false, "stops": [ + {"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"} + ]}); + if placed { + gradient["start"] = json!([160, bottom]); + gradient["end"] = json!([160, top]); + } + gradient +} + +fn eraser_placement_effects(s: &Session, owner: NodeId) -> Value { + let n = s.doc().unwrap().doc.node(owner).unwrap(); + json!({"object": n.appearance.effects, + "items": n.appearance.items.iter().map(|item| item.effects()).collect::>()}) +} + +fn eraser_placement_trim( + s: &mut Session, + edited: NodeId, + owner: NodeId, + clear: (u32, u32), +) -> (vectorcraft_render::Rendered, vectorcraft_render::Rendered) { + let before_image = eraser_gradient_image(s); + assert_eq!(before_image.pixel(clear.0, clear.1)[3], 255, "the actual effected art paints the erase witness"); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let ancestry = before.ancestry(edited).unwrap(); + let effects = eraser_placement_effects(s, owner); + let bounds = before.node(owner).unwrap().geometric_bounds().unwrap(); + assert_eq!((bounds.y0, bounds.y1), (100.0, 200.0)); + let miss = s.execute("path.eraseRegion", &json!({"rect": [10, 10, 10, 10]})).unwrap(); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = s.execute("path.eraseRegion", &json!({"rect": [50, 80, 200, 50]})).unwrap(); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "the extremal trim keeps one piece"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry); + assert!((d.node(owner).unwrap().geometric_bounds().unwrap().y0 - 130.0).abs() < 1e-5); + assert_eq!(eraser_placement_effects(s, owner), effects, "stored object and item effects stay live and identical"); + let after_image = eraser_gradient_image(s); + assert_eq!(after_image.pixel(clear.0, clear.1)[3], 0, "the witness really leaves the effected art"); + eraser_container_gradient_restore(s, &before_json, &selection, history); + (before_image, after_image) +} + +fn eraser_placement_matches( + placed: &(vectorcraft_render::Rendered, vectorcraft_render::Rendered), + fitted: &(vectorcraft_render::Rendered, vectorcraft_render::Rendered), + samples: &[(u32, u32)], +) { + for &(x, y) in samples { + assert_eq!(placed.0.pixel(x, y)[3], 255); + assert_eq!(placed.1.pixel(x, y)[3], 255, "the equivalent placed control retains the sample"); + assert_eq!(fitted.0.pixel(x, y), placed.0.pixel(x, y), "the public placed vector is equivalent BEFORE the edit at ({x},{y})"); + assert_eq!( + fitted.1.pixel(x, y), + placed.1.pixel(x, y), + "fitted and equivalent placed paint follow the SAME live effects AFTER the edit at ({x},{y})" + ); + } + assert_ne!(placed.0.pixel(samples[0].0, samples[0].1), placed.0.pixel(samples[1].0, samples[1].1)); +} + +fn eraser_placement_affine_scene(placed: bool) -> (vectorcraft_render::Rendered, vectorcraft_render::Rendered) { + let mut s = session(); + let (edited, _, owner, _) = eraser_container_gradient_fixture(&mut s, false, false); + // Offset10 makes the original aggregate fit y=90..210. The explicit control + // fixes THAT frame before the following Transform carries it, not the raw box. + s.execute( + "appearance.setItem", + &json!({"ids": [owner.0], "target": "object", "index": 0, + "gradient": eraser_placement_ramp(placed, 210.0, 90.0)}), + ) + .unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"}}), + ) + .unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "distort.transform", "params": {"scaleH": 100, "scaleV": 150, + "reference": 8, "objects": true, "copies": 0, "random": false, + "rotate": 0, "moveH": 0, "moveV": 0, "patterns": false, "strokes": false}}), + ) + .unwrap(); + let n = s.doc().unwrap().doc.node(owner).unwrap(); + assert_eq!(n.appearance.effects.len(), 2); + let transform = &n.appearance.effects[1]; + assert_eq!(transform.id, "distort.transform"); + assert!(transform.visible); + assert_eq!(transform.params["scaleV"].as_f64(), Some(150.0)); + assert_eq!(transform.params["reference"].as_f64(), Some(8.0)); + assert_eq!(transform.params["objects"].as_bool(), Some(true)); + assert_eq!(transform.params["copies"].as_f64(), Some(0.0)); + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("own Group gradient missing") }; + assert_eq!(g.geom.is_some(), placed); + // Reference8 is the bottom-right of the effected aggregate (230,210), + // unchanged by the top trim. V150 sends the original y90 edge to y30; + // without this actual affine action pixel(125,60) would be transparent. + eraser_placement_trim(&mut s, edited, owner, (125, 60)) +} + +#[test] +fn eraser_placement_control_affine_carry_matches_equivalent_placed() { + let placed = eraser_placement_affine_scene(true); + let fitted = eraser_placement_affine_scene(false); + eraser_placement_matches(&placed, &fitted, &[(190, 175), (190, 185)]); +} + +fn eraser_placement_item_stroke_scene(placed: bool) -> (vectorcraft_render::Rendered, vectorcraft_render::Rendered) { + let mut s = session(); + let id = marquee_rectangle(&mut s, true, false); + s.execute("paint.setFill", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 10})).unwrap(); + // The row's +10 geometry expands y100..200 to y90..210; Within stroke + // weight10 fits its gradient to the inflated y85..215 paint box. + s.execute( + "paint.setStroke", + &json!({"ids": [id.0], + "gradient": eraser_placement_ramp(placed, 215.0, 85.0)}), + ) + .unwrap(); + let index = s + .doc() + .unwrap() + .doc + .node(id) + .unwrap() + .appearance + .items + .iter() + .position(|item| matches!(item, vectorcraft_doc::AppearanceItem::Stroke(_))) + .unwrap(); + s.execute("paint.editGradient", &json!({"ids": [id.0], "item": index, "stroke": true, "strokeMode": "within"})).unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [id.0], "target": "object", "item": index, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"}}), + ) + .unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(n.kind, NodeKind::Path { .. })); + assert!(n.appearance.fill_paint().is_none()); + assert!(n.appearance.effects.is_empty(), "this effect belongs only to the stroke row"); + let vectorcraft_doc::AppearanceItem::Stroke(st) = &n.appearance.items[index] else { panic!("public stroke row missing") }; + assert_eq!(st.width, 10.0); + assert_eq!(st.gradient_mode, vectorcraft_doc::StrokeGradientMode::Within); + assert!(st.path_gradient().is_none(), "the test excludes Along/Across path-coordinate paint"); + assert_eq!(st.effects.len(), 1); + assert_eq!(st.effects[0].id, "path.offsetPath"); + assert!(st.effects[0].visible); + let vectorcraft_doc::color::Paint::Gradient(g) = &st.paint else { panic!("stroke gradient missing") }; + assert_eq!(g.geom.is_some(), placed); + assert!(!g.gradient.dither); + eraser_placement_trim(&mut s, id, id, (150, 90)) +} + +#[test] +fn eraser_placement_control_item_within_stroke_matches_equivalent_placed() { + let placed = eraser_placement_item_stroke_scene(true); + let fitted = eraser_placement_item_stroke_scene(false); + eraser_placement_matches(&placed, &fitted, &[(210, 175), (210, 185)]); +} + +fn eraser_mixed_gradient_hidden_stroke(s: &mut Session, id: NodeId, rasterize: bool) -> usize { + let index = s.doc().unwrap().doc.node(id).unwrap().appearance.items.iter().position(|item| !item.is_fill()).unwrap(); + s.execute( + "appearance.setItem", + &json!({"ids": [id.0], "index": index, "weight": 4, "gradient": { + "kind": "linear", "stops": [{"offset": 0, "color": "#00ff00"}, {"offset": 1, "color": "#ff00ff"}] + }}), + ) + .unwrap(); + let mode = if rasterize { "within" } else { "along" }; + s.execute("paint.editGradient", &json!({"ids": [id.0], "item": index, "stroke": true, "strokeMode": mode})).unwrap(); + if rasterize { + s.execute("effect.apply", &json!({"ids": [id.0], "target": "object", "item": index, "effect": "rasterize", "params": {}})).unwrap(); + } + s.execute("appearance.setItem", &json!({"ids": [id.0], "index": index, "visible": false})).unwrap(); + index +} + +fn eraser_mixed_gradient_rows_case(placed: bool, rasterize: bool) -> ([[u8; 4]; 2], [[u8; 4]; 2]) { + let mut s = session(); + let id = marquee_rectangle(&mut s, false, false); + let placed_geom = eraser_gradient_fill(&mut s, id, placed); + let index = eraser_mixed_gradient_hidden_stroke(&mut s, id, rasterize); + let node = s.doc().unwrap().doc.node(id).unwrap(); + assert!(!path(&s, id).is_closed(), "the fixture exercises the fill-only open-path route"); + assert!(node.appearance.has_drawn_fill()); + let hidden = node.appearance.items[index].clone(); + let vectorcraft_doc::AppearanceItem::Stroke(stroke) = &hidden else { panic!("the explicit row is a stroke") }; + assert!(!stroke.visible); + assert_eq!(stroke.width, 4.0, "the hidden row has a genuine positive stroke weight"); + assert!(matches!(stroke.paint, vectorcraft_doc::color::Paint::Gradient(_))); + assert_eq!(stroke.path_gradient().is_some(), !rasterize, "the two cases isolate the two owner-wide guard branches"); + assert_eq!( + stroke.gradient_mode, + if rasterize { vectorcraft_doc::StrokeGradientMode::Within } else { vectorcraft_doc::StrokeGradientMode::Along } + ); + assert_eq!(stroke.effects.iter().any(|e| e.visible && e.id == "rasterize"), rasterize); + assert!( + node.appearance + .items + .iter() + .all(|item| { !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(st) if st.visible && !st.paint.is_none() && st.width > 0.0) }), + "no visible painted stroke may change Eraser's area eligibility" + ); + let vectorcraft_doc::color::Paint::Gradient(fill) = node.appearance.fill_paint() else { panic!("the visible fill is a gradient") }; + assert_eq!(fill.geom.is_some(), placed); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let before_image = eraser_gradient_image(&s); + let before_colors = [before_image.pixel(150, 125), before_image.pixel(150, 175)]; + assert!(before_colors.iter().all(|color| color[3] == 255)); + assert_ne!(before_colors[0], before_colors[1], "the visible fill is a genuine nonconstant ramp"); + assert_eq!(before_image.pixel(150, 150)[3], 255); + + let miss = eraser_gradient_region(&mut s, "rect", false, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + + let result = eraser_gradient_region(&mut s, "rect", false, false); + let ids = result["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 2, "the marquee splits the filled area into two retained pieces"); + for value in ids { + let node = s.doc().unwrap().doc.node(NodeId(value.as_u64().unwrap())).unwrap(); + assert_eq!(node.appearance.items[index], hidden, "the unsupported hidden row stays byte-for-byte unchanged"); + if placed { + let vectorcraft_doc::color::Paint::Gradient(fill) = node.appearance.fill_paint() else { panic!("the fill stays a gradient") }; + assert_eq!(serde_json::to_value(fill.geom).unwrap(), placed_geom); + } + } + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(150, 150)[3], 0, "the intended fill band is erased"); + let after_colors = [after_image.pixel(150, 125), after_image.pixel(150, 175)]; + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); + (before_colors, after_colors) +} + +#[test] +fn eraser_mixed_gradient_rows_keep_visible_fill_placement() { + let placed_along = eraser_mixed_gradient_rows_case(true, false); + assert_eq!(placed_along.0, placed_along.1, "an explicitly placed fill with hidden Along stroke is the legitimate control"); + let placed_rasterize = eraser_mixed_gradient_rows_case(true, true); + assert_eq!(placed_rasterize.0, placed_rasterize.1, "an explicitly placed fill with a hidden Rasterize row remains unchanged"); + // Finish both fitted scenes, including metadata/no-op/Undo controls, before the shared color assertion. + let fitted_along = eraser_mixed_gradient_rows_case(false, false); + let fitted_rasterize = eraser_mixed_gradient_rows_case(false, true); + assert!( + fitted_along.0 == fitted_along.1 && fitted_rasterize.0 == fitted_rasterize.1, + "hidden rows must not suppress the visible fill's placement: Along {fitted_along:?}; Rasterize {fitted_rasterize:?}" + ); +} + +fn eraser_endpoint_region(s: &mut Session, mode: &str, miss: bool) -> Value { + if mode == "rect" { + let rect = if miss { json!([55, 145, 10, 10]) } else { json!([150, 140, 20, 20]) }; + s.execute("path.eraseRegion", &json!({"rect": rect})).unwrap() + } else { + let points = if miss { json!([[60, 150]]) } else { json!([[160, 150]]) }; + erase(s, json!({"points": points, "size": 20}), mode == "varied") + } +} + +fn eraser_keeps_unused_endpoint_handles_out_of_fill_case(mode: &str) { + for (closed, stroked) in [(false, false), (true, false), (false, true)] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"closed": closed, "anchors": [ + {"x": 100, "y": 100, "in": [0, 100]}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200, "out": [0, 200]} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + if stroked { + s.execute("paint.setFill", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap(); + } else { + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert_eq!(sp.closed, closed); + assert_eq!(sp.anchors.first().unwrap().h_in, Point::new(0.0, 100.0)); + assert_eq!(sp.anchors.last().unwrap().h_out, Point::new(0.0, 200.0)); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let before_image = eraser_gradient_image(&s); + assert_eq!(before_image.pixel(60, 150)[3], if closed { 255 } else { 0 }, "{mode}: fixture closure"); + assert_eq!(before_image.pixel(160, 150)[3], if stroked { 0 } else { 255 }, "{mode}: interior witness"); + + let result = eraser_endpoint_region(&mut s, mode, false); + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(160, 150)[3], 0, "{mode}: erased interior"); + assert_eq!(after_image.pixel(60, 150), before_image.pixel(60, 150), "{mode}: no new bulge or lost closed curve"); + if stroked { + assert_eq!(result["ids"], json!([]), "{mode}: the open outline misses an interior dab"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + continue; + } + assert_eq!(after_image.pixel(180, 180), [0, 0, 0, 255], "{mode}: retained fill"); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before, "{mode}: original geometry and endpoint handles restored"); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + if !closed { + let miss = eraser_endpoint_region(&mut s, mode, true); + assert_eq!(miss["ids"], json!([]), "{mode}: the phantom bulge cannot count as an intersection"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + } + } +} + +#[test] +fn eraser_keeps_unused_endpoint_handles_out_of_fill_marquee() { + eraser_keeps_unused_endpoint_handles_out_of_fill_case("rect"); +} + +#[test] +fn eraser_keeps_unused_endpoint_handles_out_of_fill_fixed_tip() { + eraser_keeps_unused_endpoint_handles_out_of_fill_case("fixed"); +} + +#[test] +fn eraser_keeps_unused_endpoint_handles_out_of_fill_varied_tip() { + eraser_keeps_unused_endpoint_handles_out_of_fill_case("varied"); +} + +fn eraser_copying_container_gradient_before_colors(before_image: &vectorcraft_render::Rendered) -> [[u8; 4]; 2] { + let before_colors = [before_image.pixel(190, 175), before_image.pixel(190, 185)]; + assert!(before_colors.iter().all(|color| color[3] == 255)); + assert_ne!(before_colors[0], before_colors[1], "the original sibling draws a nonconstant gradient"); + assert_ne!(before_colors[0], [0, 0, 0, 255], "the Group's own fill covers the black child"); + assert_eq!(before_image.pixel(125, 105)[3], 255, "the original extremal child paints the trim witness"); + assert_eq!(before_image.pixel(190, 295)[3], 255, "the translated sibling copy really paints"); + before_colors +} + +fn eraser_copying_container_gradient_child_offset(s: &mut Session, sibling: NodeId, owner: NodeId, placed: bool) { + s.execute( + "effect.apply", + &json!({"ids": [sibling.0], "target": "object", "item": null, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"}}), + ) + .unwrap(); + // The untouched sibling's live offset makes the evaluated source box + // [100,100,230,210]; the Group's raw source box is still [100,100,220,200]. + let mut gradient = eraser_placement_ramp(placed, 210.0, 100.0); + if placed { + gradient["start"] = json!([165, 210]); + gradient["end"] = json!([165, 100]); + } + s.execute("appearance.setItem", &json!({"ids": [owner.0], "target": "object", "index": 0, "gradient": gradient})).unwrap(); + let sibling_node = s.doc().unwrap().doc.node(sibling).unwrap(); + assert_eq!(sibling_node.appearance.effects.len(), 1); + assert_eq!(sibling_node.appearance.effects[0].id, "path.offsetPath"); + assert!(sibling_node.appearance.effects[0].visible); + assert_eq!(sibling_node.appearance.effects[0].params["offset"].as_f64(), Some(10.0)); +} + +fn eraser_copying_container_gradient_scene(placed: bool) -> ([[u8; 4]; 2], [[u8; 4]; 2]) { + let mut s = session(); + let (edited, sibling, owner, geom) = eraser_container_gradient_fixture(&mut s, placed, false); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "stylize.dropShadow", "params": {"x": 10, "y": 0, "blur": 0}}), + ) + .unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "distort.transform", "params": {"scaleH": 100, "scaleV": 100, + "reference": 8, "objects": true, "copies": 1, "random": false, + "rotate": 0, "moveH": 0, "moveV": 120, "patterns": false, "strokes": false}}), + ) + .unwrap(); + let n = s.doc().unwrap().doc.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert_eq!(n.appearance.effects.len(), 2); + assert_eq!(n.appearance.effects[0].id, "stylize.dropShadow"); + assert!(n.appearance.effects[0].visible); + assert_eq!(n.appearance.effects[1].id, "distort.transform"); + assert!(n.appearance.effects[1].visible); + assert_eq!(n.appearance.effects[1].params["copies"].as_f64(), Some(1.0)); + assert_eq!(n.appearance.effects[1].params["moveV"].as_f64(), Some(120.0)); + let effects = serde_json::to_value(&n.appearance.effects).unwrap(); + let before_image = eraser_gradient_image(&s); + let before_colors = eraser_copying_container_gradient_before_colors(&before_image); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let sibling_before = serde_json::to_value(before.node(sibling).unwrap()).unwrap(); + let ancestry = before.ancestry(edited).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = eraser_gradient_region(&mut s, "rect", true, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "a miss cannot pin an ancestor"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = eraser_gradient_region(&mut s, "rect", true, false); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "the extremal trim keeps one piece"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry); + assert_eq!(serde_json::to_value(d.node(sibling).unwrap()).unwrap(), sibling_before, "the sibling itself is unchanged"); + let n = d.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert!((n.geometric_bounds().unwrap().y0 - 110.0).abs() < 1e-5); + assert_eq!(serde_json::to_value(&n.appearance.effects).unwrap(), effects, "both effects stay live and unchanged"); + if placed { + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the own fill stays a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), geom, "the explicit source fit must not be rewritten"); + } + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(125, 105)[3], 0, "the intended band was erased"); + let after_colors = [after_image.pixel(190, 175), after_image.pixel(190, 185)]; + assert!(after_colors.iter().all(|color| color[3] == 255)); + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); + (before_colors, after_colors) +} + +#[test] +fn eraser_copying_container_gradient_keeps_source_fit_on_untouched_sibling() { + // The source is painted before its translated copy is made. The fixture's explicit + // [160,200] -> [160,100] fit is equivalent to the source's original fitted paint. + let placed = eraser_copying_container_gradient_scene(true); + let fitted = eraser_copying_container_gradient_scene(false); + assert_eq!(placed.0, placed.1, "the legitimate explicitly placed source fit preserves the untouched sibling"); + assert_eq!(fitted.0, placed.0, "both source fits must draw the same original sibling before editing"); + assert_eq!(fitted.1, fitted.0, "pinning a copying container must not recolor an untouched original sibling"); + assert_eq!(fitted.1, placed.1, "the fitted edit must match the equivalent explicitly placed source fit"); +} + +fn eraser_copying_container_gradient_owner_effects(n: &vectorcraft_doc::Node, nested_copy: bool) { + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert_eq!(n.appearance.effects.len(), if nested_copy { 3 } else { 2 }); + assert_eq!(n.appearance.effects[0].id, "stylize.dropShadow"); + assert!(n.appearance.effects[0].visible); + for (index, effect) in n.appearance.effects.iter().enumerate().skip(1) { + assert_eq!(effect.id, "distort.transform"); + assert!(effect.visible); + assert_eq!(effect.params["copies"].as_f64(), Some(1.0)); + let move_v = if nested_copy && index == 1 { 60.0 } else { 120.0 }; + assert_eq!(effect.params["moveV"].as_f64(), Some(move_v)); + } +} + +fn eraser_copying_container_gradient_variant_scene(placed: bool, nested_copy: bool) -> ([[u8; 4]; 2], [[u8; 4]; 2]) { + let mut s = session(); + let (edited, sibling, owner, _) = eraser_container_gradient_fixture(&mut s, placed, false); + if !nested_copy { + eraser_copying_container_gradient_child_offset(&mut s, sibling, owner, placed); + } + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "stylize.dropShadow", "params": {"x": 10, "y": 0, "blur": 0}}), + ) + .unwrap(); + if nested_copy { + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "distort.transform", "params": {"scaleH": 100, "scaleV": 100, + "reference": 8, "objects": true, "copies": 1, "random": false, + "rotate": 0, "moveH": 0, "moveV": 60, "patterns": false, "strokes": false}}), + ) + .unwrap(); + } + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "distort.transform", "params": {"scaleH": 100, "scaleV": 100, + "reference": 8, "objects": true, "copies": 1, "random": false, + "rotate": 0, "moveH": 0, "moveV": 120, "patterns": false, "strokes": false}}), + ) + .unwrap(); + let n = s.doc().unwrap().doc.node(owner).unwrap(); + eraser_copying_container_gradient_owner_effects(n, nested_copy); + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the Group owns the gradient") }; + assert_eq!(g.geom.is_some(), placed); + let geom = serde_json::to_value(g.geom).unwrap(); + let effects = serde_json::to_value(&n.appearance.effects).unwrap(); + let before_image = eraser_gradient_image(&s); + let before_colors = eraser_copying_container_gradient_before_colors(&before_image); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let sibling_before = serde_json::to_value(before.node(sibling).unwrap()).unwrap(); + let ancestry = before.ancestry(edited).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = eraser_gradient_region(&mut s, "rect", true, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "a miss cannot pin an ancestor"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = eraser_gradient_region(&mut s, "rect", true, false); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "the extremal trim keeps one piece"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry); + assert_eq!(serde_json::to_value(d.node(sibling).unwrap()).unwrap(), sibling_before, "the sibling itself is unchanged"); + let n = d.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert!((n.geometric_bounds().unwrap().y0 - 110.0).abs() < 1e-5); + assert_eq!(serde_json::to_value(&n.appearance.effects).unwrap(), effects, "both effects stay live and unchanged"); + if placed { + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the own fill stays a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), geom, "the explicit source fit must not be rewritten"); + } + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(125, 105)[3], 0, "the intended band was erased"); + let after_colors = [after_image.pixel(190, 175), after_image.pixel(190, 185)]; + assert!(after_colors.iter().all(|color| color[3] == 255)); + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); + (before_colors, after_colors) +} + +#[test] +fn eraser_copying_container_gradient_keeps_evaluated_child_source_fit() { + let placed = eraser_copying_container_gradient_variant_scene(true, false); + let fitted = eraser_copying_container_gradient_variant_scene(false, false); + assert_eq!(placed.0, placed.1, "the explicitly placed evaluated-child source fit preserves the untouched sibling"); + assert_eq!(fitted.0, placed.0, "both paints fit the evaluated source before copying"); + assert_eq!(fitted.1, fitted.0, "pinning uses evaluated child geometry, not the raw prefix box"); + assert_eq!(fitted.1, placed.1, "fitted paint matches the equivalent evaluated-source placement after editing"); +} + +#[test] +fn eraser_copying_container_gradient_keeps_source_fit_through_earlier_copy() { + // Both copying effects are eligible: the outer split still leaves the earlier + // copying Transform in its prefix. Own paint is fitted before either copy. + let placed = eraser_copying_container_gradient_variant_scene(true, true); + let fitted = eraser_copying_container_gradient_variant_scene(false, true); + assert_eq!(placed.0, placed.1, "the explicit original-source fit is unchanged by the trim"); + assert_eq!(fitted.0, placed.0, "the original source fit is equivalent before both copy stages"); + assert_eq!(fitted.1, fitted.0, "pinning follows the earlier eligible copy split as rendering does"); + assert_eq!(fitted.1, placed.1, "both live copy stages preserve the same source placement after editing"); +} + +#[test] +fn eraser_keeps_group_painted_open_paths_on_the_outline_route() { + for mode in ["fixed", "varied", "marquee"] { + for group_stroke in [false, true] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + if group_stroke { + s.execute("appearance.addStroke", &json!({"ids": [group.0], "target": "object"})).unwrap(); + s.execute( + "appearance.setItem", + &json!({"ids": [group.0], "target": "object", "index": 0, + "color": "#ff0000", "weight": 4}), + ) + .unwrap(); + } + s.execute("select.none", &json!({})).unwrap(); + assert!(!path(&s, id).is_closed()); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(id), Some(group)); + assert!(d.node(id).unwrap().appearance.stroke_paint().is_none()); + assert_eq!(d.node(group).unwrap().appearance.stroke_width(), if group_stroke { 4.0 } else { 0.0 }); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before_image = render(&s); + assert_eq!(before_image.pixel(150, 150), [0, 0, 255, 255]); + if group_stroke { + assert_eq!(before_image.pixel(150, 100), [255, 0, 0, 255], "the Group really paints the child's open outline"); + assert_eq!(before_image.pixel(99, 125)[3], 0, "the missing closing edge is not stroked"); + } + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + let selection = s.doc().unwrap().selection.clone(); + let paint = s.paint.clone(); + // This ordinary Eraser gesture hits fill, at least 30 pt from every real outline. + let result = match mode { + "marquee" => s.execute("path.eraseRegion", &json!({"rect": [130, 145, 40, 10]})).unwrap(), + _ => erase(&mut s, json!({"points": [[130, 150], [170, 150]], "size": 10}), mode == "varied"), + }; + if group_stroke { + assert_eq!(result["ids"], json!([]), "{mode}: a Group-painted open outline keeps main's miss behavior"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(render(&s).pixels, before_image.pixels); + } else { + assert!(!result["ids"].as_array().unwrap().is_empty(), "{mode}: the fill-only Group control still cuts as an area"); + let after_image = render(&s); + assert_eq!(after_image.pixel(150, 150)[3], 0); + assert_eq!(after_image.pixel(120, 125), [0, 0, 255, 255]); + } + assert_eq!(s.paint, paint); + } + } +} + +#[test] +fn eraser_ancestor_stroke_classification_keeps_container_context() { + for container in ["nested", "layer", "compound", "clip"] { + for stroke in ["painted", "hidden", "none", "zero"] { + eraser_ancestor_stroke_case(container, stroke); + } + } +} + +fn eraser_ancestor_stroke_case(container: &str, stroke: &str) { + let mut s = eraser_ancestor_stroke_scene(container, stroke); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before_image = render(&s); + assert_eq!(before_image.pixel(150, 150), [0, 0, 255, 255], "{container}/{stroke}: actual filled input"); + let outline_route = stroke == "painted" && container != "clip"; + if outline_route { + assert_eq!(before_image.pixel(150, 100), [255, 0, 0, 255], "{container}: actual ancestor stroke"); + } else if container == "clip" && stroke == "painted" { + assert_eq!(before_image.pixel(150, 90), [255, 0, 0, 255], "the ancestor paints the clipping outline"); + assert_eq!(before_image.pixel(150, 100), [0, 0, 255, 255], "the ancestor does not stroke the clipped child's outline"); + } + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + let selection = s.doc().unwrap().selection.clone(); + let paint = s.paint.clone(); + let result = erase(&mut s, json!({"points": [[130, 150], [170, 150]], "size": 10}), false); + if outline_route { + assert_eq!(result["ids"], json!([]), "{container}/{stroke}: preserve main's open-outline miss"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(render(&s).pixels, before_image.pixels); + } else { + assert!(!result["ids"].as_array().unwrap().is_empty(), "{container}/{stroke}: the eligible fill still cuts"); + let after_image = render(&s); + assert_eq!(after_image.pixel(150, 150)[3], 0, "{container}/{stroke}"); + assert_eq!(after_image.pixel(120, 125), [0, 0, 255, 255], "{container}/{stroke}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(render(&s).pixels, before_image.pixels); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(render(&s).pixel(150, 150)[3], 0); + } + assert_eq!(s.paint, paint); +} + +fn eraser_ancestor_stroke_scene(container: &str, stroke: &str) -> Session { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let mut subject = id; + if container == "compound" { + let other = s + .execute( + "path.create", + &json!({"anchors": [ + {"x": 220, "y": 100}, {"x": 240, "y": 100}, + {"x": 240, "y": 120}, {"x": 220, "y": 120} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("paint.setFill", &json!({"ids": [other], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [other], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0, other]})).unwrap(); + subject = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let NodeKind::Compound { children, .. } = &s.doc().unwrap().doc.node(subject).unwrap().kind else { + panic!("the public Make command produces a compound path") + }; + assert_eq!(children.len(), 2); + assert!(children.iter().all(|child| !child.path_data().unwrap().is_closed())); + } else if container == "clip" { + let mask = s.execute("shape.rectangle", &json!({"x": 90, "y": 90, "width": 120, "height": 120})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id.0, mask]})).unwrap(); + subject = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert!(s.doc().unwrap().doc.node(subject).unwrap().clips()); + } + let owner = if container == "layer" { + s.doc().unwrap().doc.layer_of(id).unwrap() + } else { + s.execute("select.set", &json!({"ids": [subject.0]})).unwrap(); + let inner = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + if container == "nested" { NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) } else { inner } + }; + s.execute("appearance.addStroke", &json!({"ids": [owner.0], "target": "object"})).unwrap(); + s.execute( + "appearance.setItem", + &json!({"ids": [owner.0], "target": "object", "index": 0, + "color": "#ff0000", "weight": if stroke == "zero" { 0 } else { 4 }, "visible": stroke != "hidden"}), + ) + .unwrap(); + if stroke == "none" { + s.execute("appearance.setItem", &json!({"ids": [owner.0], "target": "object", "index": 0, "none": true})).unwrap(); + } + // Select only the original open child (or the two-member compound). In the clip + // control, neither the mask nor the other container geometry is an Eraser target. + let selected = if container == "compound" { subject } else { id }; + s.execute("select.set", &json!({"ids": [selected.0]})).unwrap(); + s +} + +// Pinning-only checks: no Eraser operation or other geometry edit is performed below. +fn eraser_pinning_only_same_pixels(a: &vectorcraft_render::Rendered, b: &vectorcraft_render::Rendered, label: &str) { + let changed = (0..300).find_map(|y| (0..300).find(|&x| a.pixel(x, y) != b.pixel(x, y)).map(|x| (x, y, a.pixel(x, y), b.pixel(x, y)))); + assert_eq!(changed, None, "{label}: first changed pixel"); +} + +fn eraser_pinning_only_nested_scene(placed: bool, parent_offset: bool) -> (Session, NodeId) { + let mut s = session(); + let (_, _, owner, _) = eraser_container_gradient_fixture(&mut s, false, false); + s.execute("select.set", &json!({"ids": [owner.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + if parent_offset { + s.execute( + "effect.apply", + &json!({"ids": [outer.0], "target": "object", "item": null, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"}}), + ) + .unwrap(); + } + // These are the retained ordinary fit and the existing +10 pt evaluated fit. + let (bottom, top) = if parent_offset { (210.0, 90.0) } else { (200.0, 100.0) }; + s.execute( + "appearance.setItem", + &json!({"ids": [owner.0], "target": "object", "index": 0, + "gradient": eraser_placement_ramp(placed, bottom, top)}), + ) + .unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(owner), Some(outer), "INPUT: the gradient owner is nested in the effect owner"); + assert_eq!(doc.node(owner).unwrap().geometric_bounds().unwrap(), vectorcraft_geom::Rect::new(100.0, 100.0, 220.0, 200.0)); + assert!(doc.node(owner).unwrap().appearance.effects.is_empty(), "INPUT: the offset belongs to the enclosing Group only"); + let effects = &doc.node(outer).unwrap().appearance.effects; + assert_eq!(effects.len(), usize::from(parent_offset)); + if parent_offset { + assert_eq!(effects[0].id, "path.offsetPath"); + assert!(effects[0].visible); + assert_eq!(effects[0].params["offset"].as_f64(), Some(10.0)); + assert_eq!(effects[0].params["joins"], json!("round")); + } + let vectorcraft_doc::color::Paint::Gradient(g) = doc.node(owner).unwrap().appearance.fill_paint() else { + panic!("INPUT: the nested Group owns the gradient") + }; + assert_eq!(g.geom.is_some(), placed); + assert!(!g.gradient.dither); + (s, owner) +} + +fn eraser_pinning_only_nested_case(parent_offset: bool) { + let (s, owner) = eraser_pinning_only_nested_scene(false, parent_offset); + let (placed, placed_owner) = eraser_pinning_only_nested_scene(true, parent_offset); + let before = eraser_gradient_image(&s); + let explicit = eraser_gradient_image(&placed); + assert_eq!(before.pixel(190, 175)[3], 255, "INPUT: the retained sibling is painted"); + assert_eq!(before.pixel(190, 185)[3], 255); + assert_ne!(before.pixel(190, 175), before.pixel(190, 185), "INPUT: the fitted ramp is nonconstant"); + if parent_offset { + assert_eq!(before.pixel(190, 205)[3], 255, "INPUT: the enclosing positive offset reaches beyond the raw box"); + } + eraser_pinning_only_same_pixels(&before, &explicit, "INPUT: the independently placed control matches before pinning"); + let placed_doc = &placed.doc().unwrap().doc; + assert!( + vectorcraft_render::pinned_appearance_for_geometry_edit(placed_doc, placed_doc.node(placed_owner).unwrap()).is_none(), + "INPUT: an already explicit placement needs no pinning" + ); + let label = + if parent_offset { "PINNING_ONLY: nested Group under positive Offset Path" } else { "CONTROL: nested Group without enclosing effects" }; + eraser_pinning_only_store(&s.doc().unwrap().doc, owner, &before, !parent_offset, label); +} + +fn eraser_pinning_only_store(doc: &vectorcraft_doc::Document, owner: NodeId, before: &vectorcraft_render::Rendered, required: bool, label: &str) { + let original = serde_json::to_value(doc).unwrap(); + let node = doc.node(owner).unwrap(); + let Some(pinned) = vectorcraft_render::pinned_appearance_for_geometry_edit(doc, node) else { + assert!(!required, "INPUT: the ordinary control must pin reproducibly: {label}"); + assert_eq!(serde_json::to_value(doc).unwrap(), original); + println!("PINNING_FALLBACK: {label} remains fitted; no pixel failure established"); + return; + }; + assert_eq!(serde_json::to_value(doc).unwrap(), original, "INPUT: the public helper leaves its input unchanged"); + let vectorcraft_doc::color::Paint::Gradient(g) = pinned.fill_paint() else { panic!("INPUT: returned paint is a gradient") }; + assert!(g.geom.is_some(), "INPUT: the returned fitted gradient has an explicit placement"); + // The fixed linear fixture permits only stored gradient geometry to change, not effects or other row data. + let mut normalized = pinned.clone(); + assert_eq!(normalized.items.len(), node.appearance.items.len()); + for (after, before) in normalized.items.iter_mut().zip(&node.appearance.items) { + if let (vectorcraft_doc::color::Paint::Gradient(a), vectorcraft_doc::color::Paint::Gradient(b)) = (after.paint_mut(), before.paint()) { + a.geom = b.geom; + } + } + assert_eq!(serde_json::to_value(&normalized).unwrap(), serde_json::to_value(&node.appearance).unwrap(), "INPUT: only placement changes"); + let mut only_paint = doc.clone(); + only_paint.node_mut(owner).unwrap().appearance = pinned.into(); + let mut restored = only_paint.clone(); + restored.node_mut(owner).unwrap().appearance = node.appearance.clone(); + assert_eq!(serde_json::to_value(&restored).unwrap(), original, "INPUT: geometry, effects and every other source field are unchanged"); + let after = vectorcraft_render::Renderer::new().render(&only_paint, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + eraser_pinning_only_same_pixels(before, &after, label); +} + +#[test] +fn eraser_pinning_only_nested_gradient_matches_unchanged_render() { + // Establish the ordinary nested Group without an enclosing geometry effect FIRST. + eraser_pinning_only_nested_case(false); + // One retained positive offset, no cut, parameter search or timing measurement. + eraser_pinning_only_nested_case(true); +} + +fn eraser_pinning_only_text_clip_case(stroked: bool, no_stroke: Option<&vectorcraft_render::Rendered>) -> vectorcraft_render::Rendered { + assert_eq!(stroked, no_stroke.is_some(), "INPUT: the subject follows its no-stroke control"); + // Original clippaint.rs text, paint, font defaults and geometry; one retained ordinary scale. + let mut s = session(); + let art = s.execute("shape.rectangle", &json!({"x": 0, "y": 50, "width": 30, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [art], "color": "#ff0000"})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 10, "y": 120, "text": "Clip", "size": 72})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.all", &json!({})).unwrap(); + let owner = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [text.0], "color": "#0000ff"})).unwrap(); + if stroked { + s.execute("paint.setStroke", &json!({"ids": [text.0], "color": "#00ff00"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [text.0], "weight": 2})).unwrap(); + } else { + s.execute("paint.setStroke", &json!({"ids": [text.0], "none": true})).unwrap(); + } + s.execute("appearance.addFill", &json!({"ids": [owner.0], "target": "object"})).unwrap(); + s.execute( + "appearance.setItem", + &json!({"ids": [owner.0], "target": "object", "index": 0, "gradient": eraser_placement_ramp(false, 200.0, 100.0)}), + ) + .unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, "effect": "distort.transform", + "params": {"scaleH": 100, "scaleV": 150, "reference": 8, "objects": true, "copies": 0, + "random": false, "rotate": 0, "moveH": 0, "moveV": 0, "patterns": false, "strokes": false}}), + ) + .unwrap(); + let doc = &s.doc().unwrap().doc; + let node = doc.node(owner).unwrap(); + assert!(node.clips(), "INPUT: the source is a clipping Group"); + assert_eq!(node.children().unwrap()[0].id, text); + let t = doc.node(text).unwrap(); + let NodeKind::Text(type_) = &t.kind else { panic!("INPUT: the clipping object is type") }; + assert_eq!(type_.plain_text(), "Clip"); + assert_eq!(t.clip_paint().stroke.is_some(), stroked, "INPUT: only the character-stroke paint distinguishes the control"); + let bounds = t.geometric_bounds().unwrap(); + assert!(bounds.width() > 0.0 && bounds.height() > 0.0, "INPUT: actual font setup supplies nonempty glyph geometry"); + let effects = &node.appearance.effects; + assert_eq!(effects.len(), 1); + assert_eq!(effects[0].id, "distort.transform"); + assert!(effects[0].visible); + for (key, expected) in [("scaleH", 100.0), ("scaleV", 150.0), ("reference", 8.0), ("copies", 0.0)] { + assert_eq!(effects[0].params[key].as_f64(), Some(expected), "INPUT: accepted Transform {key}"); + } + let before = eraser_gradient_image(&s); + let background = before.pixel(299, 299); + assert_eq!(background[3], 0, "INPUT: the retained background sample is clear"); + if let Some(control) = no_stroke { + assert_eq!(control.pixel(299, 299), background, "INPUT: both unchanged renders use the same background"); + } + let mut ramp = std::collections::BTreeSet::new(); + let mut green = 0; + let mut outside_green = 0; + for y in 0..300 { + for x in 0..300 { + let p = before.pixel(x, y); + if p[3] == 255 && p[0] > 0 && p[2] > 0 && p[1] == 0 { + ramp.insert(p); + } + let painted_stroke = p[3] > 0 && p[1] > 200 && p[0] < 60 && p[2] < 60; + green += usize::from(painted_stroke); + outside_green += usize::from(painted_stroke && no_stroke.is_some_and(|control| control.pixel(x, y) == background)); + } + } + assert!(ramp.len() > 1, "INPUT: the fitted container gradient paints actual nonconstant glyph pixels"); + assert_eq!(green > 0, stroked, "INPUT: the painted-character stroke is actually visible only in the subject"); + if stroked { + assert!(outside_green > 0, "INPUT: the actual character stroke paints where the no-stroke control has only clear background"); + } + let label = + if stroked { "PINNING_ONLY: painted clipping text under nonuniform scale" } else { "CONTROL: same glyph/scale without painted-clip wrapper" }; + eraser_pinning_only_store(doc, owner, &before, !stroked, label); + before +} + +#[test] +fn eraser_pinning_only_painted_text_clip_matches_unchanged_render() { + let control = eraser_pinning_only_text_clip_case(false, None); + eraser_pinning_only_text_clip_case(true, Some(&control)); +} + +#[test] +fn eraser_pinning_only_keeps_hidden_geometry_and_raster_ancestors_supported() { + for raster in [false, true] { + let (mut s, owner) = eraser_pinning_only_nested_scene(false, !raster); + let outer = s.doc().unwrap().doc.parent_of(owner).unwrap(); + if raster { + s.execute( + "effect.apply", + &json!({"ids": [outer.0], "target": "object", "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}), + ) + .unwrap(); + } + let mut doc = (*s.doc().unwrap().doc).clone(); + if !raster { + let ancestor = doc.node_mut(outer).unwrap(); + ancestor.appearance.effects[0].visible = false; + } + let effect = &doc.node(outer).unwrap().appearance.effects[0]; + assert_eq!(doc.node(outer).unwrap().appearance.effects.len(), 1); + assert_eq!(effect.visible, raster); + if raster { + assert_eq!(effect.id, "blur.gaussian"); + assert_eq!(effect.params["radius"].as_f64(), Some(3.0)); + } else { + assert_eq!(effect.id, "path.offsetPath"); + assert_eq!(effect.params["offset"].as_f64(), Some(10.0)); + } + let before = vectorcraft_render::Renderer::new().render(&doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert_eq!(before.pixel(190, 175)[3], 255, "INPUT: ordinary gradient art remains visible"); + assert_ne!(before.pixel(190, 175), before.pixel(190, 185), "INPUT: the paint is nonconstant"); + let label = if raster { "CONTROL: visible Gaussian ancestor" } else { "CONTROL: hidden Offset Path ancestor" }; + eraser_pinning_only_store(&doc, owner, &before, true, label); + } +} diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 5b170b239e..c630c9cf43 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -38,11 +38,13 @@ pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as pub(crate) use brush::{ BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object, turn_over as turn_brush_art_over, }; +#[cfg(test)] +pub(crate) use envelope::DASH_CHECKS_MADE; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; -pub(crate) use envelope::MAX_CHECKED; pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright}; pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID}; +pub(crate) use envelope::{MAX_CHECKED, MAX_DASH_CHECKS}; pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; #[cfg(test)] pub(crate) use frames::TEXT_FRAME_SCANS; @@ -67,7 +69,7 @@ pub use read::{ #[cfg(test)] pub(crate) use style::ART_STYLE_PARSES; -pub(crate) use read::is_look_slot; +pub(crate) use read::{clip_by_type, is_look_slot}; pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number}; #[cfg(test)] diff --git a/crates/eps/src/import/ai/blend.rs b/crates/eps/src/import/ai/blend.rs index d317164d3a..c1d80a1d63 100644 --- a/crates/eps/src/import/ai/blend.rs +++ b/crates/eps/src/import/ai/blend.rs @@ -10,7 +10,8 @@ //! locally, never committed): the blend's own art on `%_` lines, a group holding the key objects //! and the spine, each object's `/ArtDictionary` naming its part (`ShapeBlendPathType`: `K` a key, //! `S` the spine) and a key's id (`ShapeBlendPathID`); then the steps drawn, a group on plain -//! lines; then `(Adobe Path Blends) 1 0 n XP` and `n` bytes as hex on `%` lines. Those bytes +//! lines; then `(Adobe Path Blends) 1 0 n XP` and `n` bytes as hex on `%` lines (`%_%` lines +//! for a blend in hidden art, as an opacity mask's is: all of it is on `%_` lines). Those bytes //! start `DCBA`. A blend whose spine was never edited has no spine part: only its keys. //! //! The reader reads the words after `DCBA` (little endian) this way. Word 1 is the spacing: 0 is diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 501b9f4b00..4a5a11940c 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -59,6 +59,16 @@ pub(crate) fn drawn_note(typed: bool) -> &'static str { pub(super) const MAX_PENDING: usize = 64; /// The most envelopes and warped text objects one import draws to check; more keep their drawn art. pub(crate) const MAX_CHECKED: usize = 256; +/// The most strokes with dashes aligned to corners one import draws to check against their drawn +/// looks (apart from [`MAX_CHECKED`]); more keep their drawn looks. +pub(crate) const MAX_DASH_CHECKS: usize = 256; + +#[cfg(test)] +thread_local! { + /// How many strokes with dashes aligned to corners have been drawn on this thread to check them + /// against their looks. + pub(crate) static DASH_CHECKS_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} /// The most rows or columns of a mesh read (Make with Mesh's own limit). const MAX_GRID: u32 = 50; /// How far, in points over width and height together, a saved size may lie from the contents' @@ -692,6 +702,8 @@ pub struct WarpedType { pub(super) checks: usize, pub(super) spent: Spent, pub(super) page: Option, + /// [`super::Structure::type_clips`]: type in an envelope's contents clips its clipping group too. + pub(super) type_clips: HashMap, /// The envelopes of type that may open live in layers built without a page, by their place /// among them ([`Self::open_alone`]): none when `None`. pub(super) alone: Option>, @@ -811,8 +823,10 @@ impl WarpedType { texts.insert(slot, text); hidden.push(id); } + let typed = |slot: NodeId| texts.get(&slot).map(|t| t.id); for n in before.iter_mut().chain(inner.iter_mut()) { put_type(n, &texts); + super::clip_by_type(n, &self.type_clips, &typed, &mut |_| ()); } // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the // grid the file saves for it: then it opens as a mesh envelope on that grid. @@ -980,10 +994,11 @@ pub(super) fn warps(appearance: &Appearance) -> bool { appearance.effects.iter().any(warp) || appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(warp)) } -/// Do `live` and `drawn` draw alike: few of the pixels either inks differ, and fewer still where a -/// whole patch differs; and, on `page` (when the file has one), do they differ little enough that -/// with the differences in `spent` the page check still takes the layers' art (it is added to -/// `spent` when they do)? Both are drawn on `layer`, a layer id no other node has. +/// Do `live` and `drawn` draw alike? Either neither has any paint ([`paints`]), or few of the +/// pixels either inks differ and fewer still where a whole patch differs, and, on `page` (when the +/// file has one), they differ little enough that with the differences in `spent` the page check +/// still takes the layers' art (it is added to `spent` when they do). Both are drawn on `layer`, a +/// layer id no other node has. pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { alike_within(live, drawn, live.visual_bounds(), layer, shared, page, spent) } @@ -997,6 +1012,12 @@ pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Sh /// [`drawn_alike`], with `live` measured as `reach`. fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { + // Neither has any paint (type with no fill and no stroke, its drawn art the outlines unpainted): + // both draw nothing, so they draw alike and add nothing to what the page check sees. Their + // shapes aren't compared. Art that paints, however faintly, is compared as before. + if !paints(live, 0) && !paints(drawn, 0) { + return true; + } let (Some(a), Some(b)) = (reach, drawn.visual_bounds()) else { return false }; let region = a.union(b).inflate(2.0, 2.0); if !(region.is_finite() && region.width() > 0.0 && region.height() > 0.0) || region.width().max(region.height()) > 1e6 { @@ -1029,6 +1050,26 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, s true } +/// Does `n`, shown, paint anything: a fill or stroke of its own or of its type with a paint, an +/// effect, or an object of another kind than a path, type or container (an image, a mesh, a symbol +/// instance…)? Hidden objects paint nothing. Past `depth` 64 it is taken to paint. +fn paints(n: &Node, depth: usize) -> bool { + if depth > 64 { + return true; + } + if !n.visible { + return false; + } + if n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()) || n.appearance.effects.iter().any(|e| e.visible) { + return true; + } + match &n.kind { + NodeKind::Path { .. } => false, + NodeKind::Text(t) => t.runs.iter().any(|r| !r.style.fill.is_none() || !r.style.stroke.is_none()), + _ => n.children().is_none_or(|c| c.iter().any(|c| paints(c, depth + 1))), + } +} + #[cfg(test)] mod tests { use super::*; @@ -1056,6 +1097,41 @@ mod tests { } } + /// A 40 × 40 square at (10, 10) filled black at `opacity`, or with no fill when `None`. + fn square_node(id: u64, opacity: Option) -> Node { + let mut bp = BezPath::new(); + bp.move_to((10.0, 10.0)); + bp.line_to((50.0, 10.0)); + bp.line_to((50.0, 50.0)); + bp.line_to((10.0, 50.0)); + bp.close_path(); + let mut n = Node::new( + NodeId(id), + NodeKind::Path { path: PathData::from_bezpath(&bp), rule: Default::default(), live: None, clipping: false, guide: false }, + ); + let mut appearance = (*n.appearance).clone(); + appearance.items.clear(); + if let Some(o) = opacity { + appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)))); + n.opacity = o; + } + n.appearance = appearance.into(); + n + } + + /// Two objects with no paint draw alike; two that paint too faintly to ink a pixel (an alpha of + /// 8 or less) aren't taken as alike, nor is one with paint against one without. + #[test] + fn art_with_no_paint_draws_alike_and_faint_art_is_still_compared() { + let shared = Shared { patterns: &[], images: &BTreeMap::new() }; + let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, None, &mut Spent::default()); + let (none, other_none) = (square_node(1, None), square_node(2, None)); + assert!(alike(&none, &other_none)); + let (faint, other_faint) = (square_node(1, Some(0.02)), square_node(2, Some(0.02))); + assert!(!alike(&faint, &other_faint)); + assert!(!alike(&none, &square_node(2, Some(1.0)))); + } + /// "AVA" at 40 points, at (10, 60). fn type_node(id: u64, style: CharStyle) -> Node { Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "AVA", CharStyle { size: 40.0, ..style })))) diff --git a/crates/eps/src/import/ai/lex.rs b/crates/eps/src/import/ai/lex.rs index 810a01c3f2..a43166ccc9 100644 --- a/crates/eps/src/import/ai/lex.rs +++ b/crates/eps/src/import/ai/lex.rs @@ -5,7 +5,8 @@ //! - Any other line starting with `%` is a [`Tok::Comment`] (the section markers). //! - `%_` later in a line starts tokens too, hidden (a pseudo-comment operator after its //! operands, as a gradient stop's `… 50 100 %_Bs`: AI7 spec §1.4.3); any other `%` later in a -//! line starts a comment that is skipped. +//! line starts a comment that is skipped, but for a line of hex digits after `%_` (a hidden +//! blend's record), a hidden [`Tok::Comment`]. //! - The binary image data after `%%BeginData:` is one [`Tok::Data`]; the binary preview of a placed //! file is one [`Tok::Preview`]. //! - A document included whole (`%%BeginDocument:` … `%%EndDocument` lines, DSC 3.0 p. 68, nested @@ -222,6 +223,12 @@ impl<'a> Lexer<'a> { if prefixed && PLACE.iter().chain(&NOTES).chain(&RELATIVE).any(|m| line.starts_with(m)) { return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: true }); } + // And a line of hex digits, as a hidden blend's record is written (`%_%4443…` + // after its `XP`), like the plain one on `%` lines. + let digits = line.get(1..).unwrap_or_default(); + if prefixed && !digits.trim_ascii_end().is_empty() && digits.trim_ascii_end().iter().all(u8::is_ascii_hexdigit) { + return Some(Token { tok: Tok::Comment(digits), hidden: true }); + } // A comment later in a line. continue; } @@ -470,6 +477,10 @@ mod tests { let toks = all(b"1 % a note (\n2 %_Bs\n3 %_ 4\n"); let words: Vec<_> = toks.iter().map(|t| (t.tok.clone(), t.hidden)).collect(); assert_eq!(words, [(Tok::Num(1.0), false), (Tok::Num(2.0), false), (Tok::Word(b"Bs"), true), (Tok::Num(3.0), false)]); + // A hidden line of hex digits (a hidden blend's record) is a comment; other text after + // `%_%` stays skipped. + let toks = all(b"%_%44434241\n%_% not hex\n%_%\n1\n"); + assert_eq!(toks, [t(Tok::Comment(b"44434241"), true), t(Tok::Num(1.0), false)]); } #[test] diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index cc43157bcb..b354022258 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -195,6 +195,10 @@ pub struct Structure { pub unread_elsewhere: Vec<(NodeId, Rect)>, /// The names of text objects, by their slot's id. pub slot_names: HashMap, + /// The clipping groups whose type clips them, by the group's id: the text slot of that type, + /// the group's last object ([`Reader::end_container`]). Once the slot holds its type, the type + /// clips the group ([`clip_by_type`]). + pub type_clips: HashMap, /// Where the drawn looks lay that objects read with their art style took the place of (the /// document's coordinates): the page draws Illustrator's rendering of those styles there. pub restyled: Vec, @@ -595,6 +599,13 @@ struct Reader<'a> { envelope_checks: usize, /// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]). envelope_spent: super::envelope::Spent, + /// How many more strokes with dashes aligned to corners this import may draw to check + /// ([`super::MAX_DASH_CHECKS`]). + dash_checks: usize, + /// Whether this reader reads only what comes before the first layer (swatches, brushes, styles, + /// symbols) for a file whose layers another reader reads: it makes no more checks once it + /// reaches the layers, so it spends none of theirs. + defs_only: bool, /// The text objects read with a Warp ([`super::envelope::WarpedType`]). warped_type: Vec, /// The envelopes of type read with their drawn art, settled once the type is laid out @@ -662,6 +673,8 @@ struct Reader<'a> { obj_hidden: bool, /// The names of text objects, by their slot's id. slot_names: HashMap, + /// [`Structure::type_clips`]. + type_clips: HashMap, /// [`Structure::xml_ids`]. xml_ids: HashMap>, /// The bytes of the ids in `xml_ids`. @@ -732,6 +745,40 @@ pub(crate) fn is_look_slot(name: Option<&str>) -> bool { name == Some(document::LOOK_SLOT) } +/// Make the clipping groups of [`Structure::type_clips`] in `n` and its groups clip by their type, +/// once their slots are filled: where a group's slot became one text object (`typed` gives its id by +/// the slot's) that is still the group's last object, that text object moves to the front as its +/// clipping path, and `clipping` is called on it. Where the slot was left empty or became several +/// objects, the group stays as read, unclipped. How many groups clip. +pub(crate) fn clip_by_type( + n: &mut Node, + clips: &HashMap, + typed: &impl Fn(NodeId) -> Option, + clipping: &mut impl FnMut(&mut Node), +) -> usize { + if clips.is_empty() || matches!(n.kind, NodeKind::Compound { .. }) { + return 0; + } + let mut made = 0; + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| c.children().is_some_and(|k| !k.is_empty())) { + made += clip_by_type(Arc::make_mut(c), clips, typed, clipping); + } + } + let Some(text) = clips.get(&n.id).and_then(|slot| typed(*slot)) else { return made }; + if let NodeKind::Group { children, clip } = &mut n.kind + && !*clip + && children.last().is_some_and(|last| last.id == text && matches!(last.kind, NodeKind::Text(_))) + && let Some(mut last) = children.pop() + { + clipping(Arc::make_mut(&mut last)); + children.insert(0, last); + *clip = true; + made += 1; + } + made +} + impl<'a> Reader<'a> { /// A reader of the editing data `data` as a whole, with the names its gradients and patterns /// get in the document and its art styles found first ([`swatch_names`]): the symbols defined @@ -824,6 +871,8 @@ impl<'a> Reader<'a> { envelopes: Vec::new(), envelope_checks: super::envelope::MAX_CHECKED, envelope_spent: super::envelope::Spent::default(), + dash_checks: super::MAX_DASH_CHECKS, + defs_only: false, warped_type: Vec::new(), typed_envelopes: Vec::new(), envelopes_drawn: Vec::new(), @@ -853,6 +902,7 @@ impl<'a> Reader<'a> { done: false, obj_hidden: false, slot_names: HashMap::new(), + type_clips: HashMap::new(), xml_ids: HashMap::new(), xml_id_bytes: 0, art_size: None, diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 9db1470093..46743e9d70 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -16,6 +16,9 @@ impl<'a> Reader<'a> { if matches!(kind, Kind::Layer(_)) { self.ensure_space(); self.check_symbols(); + if self.defs_only { + (self.envelope_checks, self.dash_checks) = (0, 0); + } } let base = if matches!(kind, Kind::Obj(_)) { self.stack.len() } else { self.frames.last().map_or(0, |f| f.base) }; self.frames.push(Frame { @@ -120,11 +123,13 @@ impl<'a> Reader<'a> { } // A group holding only clipping paths (`q … u W n U … Q`) doesn't clip on its own: `u`/`U` don't save // the graphics state as `q`/`Q` do, so its paths clip the clipping group around it, as the file's PDF part draws it. + // In a compound path (`*u u W n … U *U`, possibly nested in other groups) they are the compound + // path's subpaths, as its other grouped paths are: the compound clipping path, their union. if matches!(kind, Kind::Group) && unread.is_empty() && !clips.is_empty() && clips.len() == kids.len() - && matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) + && (matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) || self.in_compound()) { for kid in kids { if let Some(parent) = self.frames.last_mut() { @@ -134,6 +139,15 @@ impl<'a> Reader<'a> { } return Ok(()); } + // A clipping group (`q` … `Q`) with no clipping path whose last object is type: that type is + // its clipping path, as Illustrator writes a clipping mask of type made from the text + // document (`/AI11Text`), which has no `W`. The slot is filled later ([`clip_by_type`]). + let type_clip = match kids.last() { + Some(last) if matches!(kind, Kind::Clip) && clips.is_empty() && !super::is_look_slot(last.name.as_deref()) => { + slot_of(last.name.as_deref()).map(|_| last.id) + } + _ => None, + }; // A compound path of clipping paths clips its clipping group. let clipping = matches!(kind, Kind::Compound) && !clips.is_empty(); self.group_ended = !matches!(kind, Kind::Compound); @@ -179,6 +193,9 @@ impl<'a> Reader<'a> { if clipping && let Some(f) = self.frames.last_mut() { f.clips.push(f.children.len()); } + if let Some(slot) = type_clip { + self.type_clips.insert(node.id, slot); + } if compound_members { self.compound_groups.insert(node.id); } @@ -197,6 +214,18 @@ impl<'a> Reader<'a> { Ok(()) } + /// Is the innermost open frame a compound path (`*u`), or a group in one with only groups between them? + fn in_compound(&self) -> bool { + for f in self.frames.iter().rev() { + match f.kind { + Kind::Group => {} + Kind::Compound => return true, + _ => return false, + } + } + false + } + /// The compound path of `kids`, painted and made transparent as its subpaths say. fn compound(&mut self, mut kids: Vec, gs: &GState) -> Option { // The compound path's paint is its last path's (a gradient's instance wraps only diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 8ca3781717..67b3e799e2 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -837,11 +837,13 @@ impl<'a> Reader<'a> { } /// Lend `sub`, a reader of a definition, what this import may still spend on laying out blends - /// and checking envelopes ([`Reader::take_back_budgets`] takes back what is left). + /// and checking envelopes and aligned dashes ([`Reader::take_back_budgets`] takes back what is + /// left). fn lend_budgets(&mut self, sub: &mut Reader<'_>) { sub.blend_budget = self.blend_budget; sub.envelope_checks = self.envelope_checks; sub.envelope_spent = std::mem::take(&mut self.envelope_spent); + sub.dash_checks = self.dash_checks; } /// Take back from `sub` what [`Self::lend_budgets`] lent it, less what it spent. @@ -849,6 +851,7 @@ impl<'a> Reader<'a> { self.blend_budget = sub.blend_budget; self.envelope_checks = sub.envelope_checks; self.envelope_spent = std::mem::take(&mut sub.envelope_spent); + self.dash_checks = sub.dash_checks; } /// In a pattern's definition, the operands of its first operator start with its head, diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index f3684f3882..2eee5a0a15 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -336,6 +336,7 @@ fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap) { /// those the swatches take. pub fn palette(data: &[u8], patterns: &[PatternDef], names: &mut obj::Names) -> Option { let mut r = Reader::with_names(data, names.encoding); + r.defs_only = true; // The palette, the gradients and the patterns it names come before the art, so an error in the // art leaves them read. let _ = r.run(); @@ -396,6 +397,7 @@ pub fn brushes(data: &[u8], patterns: &[PatternDef], names: &mut obj::Names) -> // Brush objects are plug-in objects: data without one isn't read again. memchr::memmem::find(data, b"BeginPluginObject")?; let mut r = Reader::with_names(data, names.encoding); + r.defs_only = true; // The brushes come before the art, so an error in the art leaves them read. let _ = r.run(); let (mut lib, unread) = r.brush_library()?; @@ -449,6 +451,7 @@ pub fn graphic_styles(data: &[u8], large_canvas: bool, names: &mut obj::Names) - return (vec![], 1.0); } let mut r = Reader::with_names(data, names.encoding); + r.defs_only = true; r.large_canvas = large_canvas.then_some(1.0); // The styles come before the art, so an error in the art leaves them read. let _ = r.run(); @@ -482,6 +485,7 @@ pub struct Symbols { pub fn symbols(data: &[u8], names: &mut obj::Names) -> Option { crate::import::ai::find(data, b"BeginSymbol")?; let mut r = Reader::with_names(data, names.encoding); + r.defs_only = true; // The symbols come before the art, so an error in the art leaves them read. let _ = r.run(); r.check_symbols(); @@ -536,10 +540,20 @@ pub fn symbols(data: &[u8], names: &mut obj::Names) -> Option { Some(Symbols { symbols, images, swatches, canvas_scale: r.canvas_scale, own_size: r.symbols_own_size }) } +/// A reader of all of `data` for what doesn't depend on how its art draws (its artboards, its +/// variable library): it checks no envelope and no stroke with aligned dashes against its drawn +/// look, so it spends none of the import's checks ([`super::MAX_CHECKED`], +/// [`super::MAX_DASH_CHECKS`]), which are the layers' reader's. +fn reader_aside(data: &[u8]) -> Reader<'_> { + let mut r = Reader::new(data); + (r.envelope_checks, r.dash_checks) = (0, 0); + r +} + /// [`artboards`] as far as reading `data` from its start gets: those read before an error, and /// those of a `/Document` still open when it stopped (its art can be what stopped it). fn artboards_read(data: &[u8], names: &mut obj::Names) -> (Vec<(String, Rect)>, Option) { - let mut r = Reader::new(data); + let mut r = reader_aside(data); r.names = obj::Names::new(names.encoding); let _ = r.run(); let open: Vec = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect(); @@ -608,7 +622,7 @@ pub fn variables(data: &[u8], names: &mut obj::Names) -> VariableRead { if crate::import::ai::find(data, b"variableSets").is_none() { return VariableRead::default(); } - let mut r = Reader::new(data); + let mut r = reader_aside(data); r.names = obj::Names::new(names.encoding); let _ = r.run(); if r.variables.present { @@ -1385,6 +1399,7 @@ impl<'a> Reader<'a> { unread: self.unread, unread_elsewhere: self.unread_elsewhere, slot_names: self.slot_names, + type_clips: self.type_clips.clone(), restyled: self.restyled, placeholders: self.placeholders, placed_elsewhere: self.placed_elsewhere, @@ -1397,6 +1412,7 @@ impl<'a> Reader<'a> { spent: self.envelope_spent, page, alone: None, + type_clips: self.type_clips, }, styles_read, text_patterns, @@ -1960,6 +1976,20 @@ impl LibraryWalk { } } +/// Whether an XML node in `o` or the dictionaries it holds has a value or a type +/// (`xmlnode-nodevalue`, `xmlnode-nodetype`). `seen` counts the dictionaries looked at; past +/// [`MAX_LIBRARY_NODES`] of them, or deeper than [`MAX_DEPTH`], the library is taken to hold some. +fn holds_values(o: &Obj, seen: &mut usize, depth: usize) -> bool { + *seen = seen.saturating_add(1); + if *seen > MAX_LIBRARY_NODES || depth > MAX_DEPTH { + return true; + } + if o.ty == "XMLNode" && (o.get("xmlnode-nodevalue").is_some() || o.get("xmlnode-nodetype").is_some()) { + return true; + } + o.items().any(|c| holds_values(c, seen, depth + 1)) +} + /// The library of the `variableSets` element `sets` (see [`variable_library`]). fn read_variable_sets(sets: &Obj) -> VariableRead { let mut walk = LibraryWalk::default(); @@ -1979,5 +2009,34 @@ fn read_variable_sets(sets: &Obj) -> VariableRead { if walk.nodes > MAX_LIBRARY_NODES { return VariableRead { variables: Variables::default(), bindings: vec![], bindings_skipped: 0, skipped: 1, present: true }; } + if vars == Variables::default() && walk.bindings.is_empty() && !holds_values(sets, &mut 0, 0) { + // The empty library a file can keep: nodes with names and nothing else (no value, no + // type). There is nothing in it to list, so nothing was left out. + walk.skipped = 0; + } VariableRead { variables: vars, bindings: walk.bindings, bindings_skipped: walk.bindings_skipped, skipped: walk.skipped, present: true } } + +#[cfg(test)] +mod tests { + use super::*; + use std::rc::Rc; + + /// An XML node holding `child` (when given) and nothing else: no value, no type. + fn node(child: Option) -> Obj { + let children = Obj { ty: "Array".into(), content: child.map(|c| V::Obj(Rc::new(c))).into_iter().collect(), ..Obj::default() }; + Obj { ty: "XMLNode".into(), entries: vec![(Some("xmlnode-children".into()), vec![V::Obj(Rc::new(children))])], ..Obj::default() } + } + + /// An empty library is taken to hold values past the caps on what is looked at: nested deeper + /// than [`MAX_DEPTH`], or once [`MAX_LIBRARY_NODES`] dictionaries have been looked at. + #[test] + fn an_empty_library_past_the_caps_is_taken_to_hold_values() { + let shallow = node(Some(node(None))); + assert!(!holds_values(&shallow, &mut 0, 0)); + let deep = (0..MAX_DEPTH).fold(node(None), |inner, _| node(Some(inner))); + assert!(holds_values(&deep, &mut 0, 0)); + let mut seen = MAX_LIBRARY_NODES; + assert!(holds_values(&shallow, &mut seen, 0)); + } +} diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 5283762a51..101d924d60 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -832,15 +832,32 @@ impl<'a> Reader<'a> { }) }); // An image with a Warp is the object only where its live warp draws as its drawn look, and - // while the import has a check left for it; otherwise its drawn look stays. + // while the import has a check left for it; otherwise its drawn look stays. So is a stroke + // with dashes aligned to corners and path ends, whose fitting is VectorCraft's own, within + // checks of its own ([`crate::import::ai::MAX_DASH_CHECKS`]) and without weighing the page: + // the envelopes' checks and share of the page check stay theirs alone. Type with such + // dashes keeps its drawn look, as before. let appearance = match appearance { + Some(ap) if aligns_dashes(&ap) && slot_of(object.name.as_deref()).is_some() => None, Some(ap) if matches!(object.kind, NodeKind::Image(_)) && ap.effects.iter().any(|e| e.id.starts_with("warp.")) => { let alike = self.envelope_checks > 0 && { self.envelope_checks -= 1; let layer = self.doc.alloc_id(); let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; let shown = !hidden && object.visible && look.visible; - image_warp_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + }; + alike.then_some(ap) + } + Some(ap) if aligns_dashes(&ap) => { + let alike = self.dash_checks > 0 && { + self.dash_checks -= 1; + #[cfg(test)] + crate::import::ai::DASH_CHECKS_MADE.set(crate::import::ai::DASH_CHECKS_MADE.get() + 1); + let layer = self.doc.alloc_id(); + let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; + let mut spent = crate::import::ai::envelope::Spent::default(); + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, None, &mut spent) }; alike.then_some(ap) } @@ -1062,23 +1079,35 @@ fn tick(vals: &[V]) -> Option<(Affine, Rect, String)> { } /// The gradients and patterns `look` paints with, placed as it draws them, by their swatch's name -/// (the first of each; a pattern's name after `PATTERN_KEY`). -fn placed_paints(look: &Node, out: &mut HashMap, depth: usize) { +/// (the first of each; a pattern's name after `PATTERN_KEY`). With `fill_patterns`, a pattern only +/// where the look fills with it: a style's pattern is a fill, so a path's stack takes it from the +/// look's fills alone (type keeps taking it from either). `moved` gets each pattern that the look +/// also places elsewhere than its first placement. +fn placed_paints(look: &Node, out: &mut HashMap, moved: &mut HashSet, fill_patterns: bool, depth: usize) { if depth > MAX_DEPTH { return; } for item in &look.appearance.items { let key = match item.paint() { Paint::Gradient(g) => g.swatch.clone(), - Paint::Pattern { pattern, .. } => Some(format!("{PATTERN_KEY}{pattern}")), + Paint::Pattern { pattern, .. } if item.is_fill() || !fill_patterns => Some(format!("{PATTERN_KEY}{pattern}")), _ => None, }; if let Some(key) = key { - out.entry(key).or_insert_with(|| item.paint().clone()); + match out.get(&key) { + Some(first) => { + if matches!(first, Paint::Pattern { .. }) && first != item.paint() { + moved.insert(key); + } + } + None => { + out.insert(key, item.paint().clone()); + } + } } } for c in look.children().into_iter().flatten() { - placed_paints(c, out, depth + 1); + placed_paints(c, out, moved, fill_patterns, depth + 1); } } @@ -1224,18 +1253,19 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { /// Is `object` an image without an opacity mask, and `st` one Warp on it with nothing else that /// paints ([`crate::import::ai::style::ArtStyle::image_warp`])? Such an image is read with its Warp -/// live where that draws as its drawn look ([`image_warp_alike`]). +/// live where that draws as its drawn look ([`look_alike`]). fn image_warps(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { matches!(object.kind, NodeKind::Image(_)) && object.extras().mask.is_none() && st.image_warp } -/// Does image `object` with `appearance` (its style's Warp) draw as `look`, its drawn look, compared -/// over all that the warp draws ([`crate::import::ai::envelope::warped_alike`]) on `layer`, a layer -/// id no other node has? Both are drawn shown, opaque and in the Normal mode; a hidden look is drawn -/// with every object in it shown, as the hidden object's look holds them. Unless the look is on -/// `%_` lines itself (`hidden`), the copies in it that are on `%_` lines (`hidden_ids`) are left out. +/// Does `object` with `appearance` (an image's Warp, or a stroke with dashes aligned to corners) +/// draw as `look`, its drawn look, compared over all that it draws, effects included +/// ([`crate::import::ai::envelope::warped_alike`]), on `layer`, a layer id no other node has? Both +/// are drawn shown, opaque and in the Normal mode; a hidden look is drawn with every object in it +/// shown, as the hidden object's look holds them. Unless the look is on `%_` lines itself +/// (`hidden`), the copies in it that are on `%_` lines (`hidden_ids`) are left out. #[allow(clippy::too_many_arguments)] -fn image_warp_alike( +fn look_alike( object: &Node, appearance: &Appearance, look: &Node, @@ -1261,6 +1291,11 @@ fn image_warp_alike( crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent) } +/// Does `appearance` stroke with dashes aligned to corners and path ends? +fn aligns_dashes(appearance: &Appearance) -> bool { + appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.dash.as_ref().is_some_and(|d| d.align_corners && d.is_dashed()))) +} + /// Show every object in container `n`, at any depth. fn show_members(n: &mut Node) { for c in n.children_mut().into_iter().flatten() { @@ -1282,7 +1317,7 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let slot = slot_of(object.name.as_deref()).is_some(); // Several fills and strokes, on a path or a compound path. let stacked = !slot && !st.simple && st.stacked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); - // One Warp on an image, checked against its drawn look by the caller ([`image_warp_alike`]). + // One Warp on an image, checked against its drawn look by the caller ([`look_alike`]). let image_warp = !st.simple && image_warps(object, st); // A symbol instance draws its symbol's art: it keeps its drawn look. if !st.plain @@ -1301,15 +1336,22 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let own_gradient = object.appearance.fill().filter(|f| matches!(f.paint, Paint::Gradient(_))); // A style's gradients are written in a space of the object's bounds that isn't documented; its // drawn look has each where the app placed it. - let mut placed = HashMap::new(); - placed_paints(look, &mut placed, 0); + let (mut placed, mut moved) = (HashMap::new(), HashSet::new()); + placed_paints(look, &mut placed, &mut moved, stacked, 0); // A stack's gradients are each its own swatch, placed where the drawn look has it: one fitted - // to the object's bounds instead could lie elsewhere, so such a stack keeps its drawn look. + // to the object's bounds instead could lie elsewhere, so such a stack keeps its drawn look. So + // are its patterns, each once, and each placed one way in the look: `placed_paints` keeps the + // first placement of each name, and which of several is the style's isn't known. The same + // placement again (a compound path's look fills each subpath) is still one. if stacked { - let mut seen = HashSet::new(); + let (mut seen, mut seen_patterns) = (HashSet::new(), HashSet::new()); let placed_apart = st.items.iter().all(|i| match i { StyleItem::Gradient { name: Some(n), .. } => seen.insert(n) && placed.contains_key(paints.names.get(Global::Gradient, n)), StyleItem::Gradient { name: None, .. } => false, + StyleItem::Pattern { name, .. } => { + let key = format!("{PATTERN_KEY}{}", paints.names.get(Global::Pattern, name)); + seen_patterns.insert(key.clone()) && placed.contains_key(&key) && !moved.contains(&key) + } _ => true, }); if !placed_apart { @@ -1382,7 +1424,134 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p } else { object.appearance.contents_index }; - Some(Appearance { items, effects: st.effects.clone(), contents_index }) + let appearance = Appearance { items, effects: st.effects.clone(), contents_index }; + // Zig Zag's ridges are placed by VectorCraft's own rule: on objects other than type it is kept + // only where they draw the outline the drawn look has. + if !slot && st.effects.iter().any(|e| e.id == "distort.zigZag") && !draws_look_outline(object, &appearance, look) { + return None; + } + Some(appearance) +} + +/// How far, in points, an outline drawn with a reshaping effect may lie from its drawn look's +/// ([`draws_look_outline`]): the look's coordinates are written to a few decimals. +const OUTLINE_TOLERANCE: f64 = 0.25; + +/// How far, in points, a flattened outline in [`draws_look_outline`] may lie from its curves. +const OUTLINE_FLATNESS: f64 = OUTLINE_TOLERANCE / 10.0; + +/// How far apart, in points, [`draws_look_outline`] checks points along each flattened segment. +const OUTLINE_SPACING: f64 = OUTLINE_TOLERANCE / 2.0; + +/// How close, in points, each checked point must lie to the other flattened outline: every point +/// between two checked ones is within half the spacing of one, and both outlines are within the +/// flatness of their curves, so the curves are then within [`OUTLINE_TOLERANCE`] of each other. +const OUTLINE_POINT_LIMIT: f64 = OUTLINE_TOLERANCE - 2.0 * OUTLINE_FLATNESS - OUTLINE_SPACING / 2.0; + +/// Most point-to-segment distances worked out for one object, over all its look's outlines. +const MAX_OUTLINE_PAIRS: usize = 4_000_000; + +/// Does path or compound path `object` with `appearance`'s effects draw every outline of its drawn look +/// `look`, as `look` draws its own (each within [`OUTLINE_TOLERANCE`] of the other)? `false` for +/// anything else: a look holding other than paths, outlines too detailed to compare. +fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bool { + fn leaves(n: &Node, out: &mut Vec, depth: usize) -> bool { + match &n.kind { + NodeKind::Path { path, .. } => { + out.push(path.clone()); + true + } + NodeKind::Compound { children, .. } => { + out.push(vectorcraft_geom::PathData::new( + children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect(), + )); + true + } + NodeKind::Group { clip: false, .. } if depth < MAX_DEPTH => n.children().into_iter().flatten().all(|c| leaves(c, out, depth + 1)), + _ => false, + } + } + /// The segments of `paths` flattened, at most `max` of them. + fn segments(paths: &[vectorcraft_geom::PathData], max: usize) -> Option> { + let mut out = vec![]; + let (mut start, mut last) = (None, None); + let mut over = false; + for p in paths { + vectorcraft_geom::flatten(p.to_bezpath(), OUTLINE_FLATNESS, |el| { + let mut add = |a: kurbo::Point, b: kurbo::Point| { + if out.len() < max { + out.push(kurbo::Line::new(a, b)); + } else { + over = true; + } + }; + match el { + kurbo::PathEl::MoveTo(q) => (start, last) = (Some(q), Some(q)), + kurbo::PathEl::LineTo(q) => { + if let Some(l) = last { + add(l, q); + } + last = Some(q); + } + kurbo::PathEl::ClosePath => { + if let (Some(l), Some(s)) = (last, start) { + add(l, s); + } + last = start; + } + _ => {} + } + }); + } + (!over && !out.is_empty()).then_some(out) + } + /// Does every point of segments `a` lie close enough to segments `b` ([`OUTLINE_POINT_LIMIT`])? + /// Each segment is checked at both ends (the last point of an open outline starts no segment) + /// and at points at most [`OUTLINE_SPACING`] apart between them (two outlines can share their + /// vertices and join them differently). Each point's distance to each segment of `b` (a + /// projection onto it) is taken from `budget`: `false` once that runs out. + fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool { + use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT); + for s in a { + let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil(); + let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 }; + let Some(left) = budget.checked_sub(steps.saturating_add(1).saturating_mul(b.len())) else { return false }; + *budget = left; + if !(0..=steps).all(|k| close(s.eval(k as f64 / steps as f64))) { + return false; + } + } + true + } + /// The box round segments `lines` (`None` without any). + fn bounds(lines: &[kurbo::Line]) -> Option { + let first = lines.first()?.p0; + Some(lines.iter().fold(kurbo::Rect::from_points(first, first), |r, l| r.union_pt(l.p0).union_pt(l.p1))) + } + let (mut ours, mut theirs) = (vec![], vec![]); + if !matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !leaves(object, &mut ours, 0) || !leaves(look, &mut theirs, 0) { + return false; + } + // The object's outline reshaped as it is drawn: its effects from its own bounds. + for path in &mut ours { + let bounds = kurbo::Shape::bounding_box(&path.to_bezpath()); + *path = vectorcraft_effects::apply_geometry(&appearance.effects, path, bounds); + } + let max = MAX_OUTLINE_PAIRS.isqrt(); + let Some(ours) = segments(&ours, max) else { return false }; + let Some(ours_box) = bounds(&ours) else { return false }; + // Two outlines each within the tolerance of the other have boxes as close: the boxes are + // compared first, then the points, from one budget for the object. + let boxed = |t: &[kurbo::Line]| { + let Some(r) = bounds(t) else { return false }; + [r.x0 - ours_box.x0, r.y0 - ours_box.y0, r.x1 - ours_box.x1, r.y1 - ours_box.y1].iter().all(|d| d.abs() <= OUTLINE_TOLERANCE) + }; + let mut budget = MAX_OUTLINE_PAIRS; + // Each of the look's outlines (a fill and a stroke draw the same one) is the object's. + theirs + .iter() + .all(|t| segments(std::slice::from_ref(t), max).is_some_and(|t| boxed(&t) && near(&t, &ours, &mut budget) && near(&ours, &t, &mut budget))) } /// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one @@ -1673,6 +1842,50 @@ mod tests { Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0))) } + /// The outline check works from one budget for the object: a look of the outline drawn twice + /// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn + /// look instead of comparing every copy. + #[test] + fn the_outline_check_has_one_budget_for_the_object() { + let zig = vectorcraft_doc::Effect { + id: "distort.zigZag".into(), + params: serde_json::json!({"size": 3.0, "relative": false, "ridges": 4, "points": "corner"}), + visible: true, + }; + let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 60.0)); + let appearance = Appearance { effects: vec![zig.clone()], ..Appearance::basic(Paint::None, Paint::None, 0.0) }; + let object = Node::path(NodeId(1), path.clone(), appearance.clone()); + let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &path, Rect::new(0.0, 0.0, 100.0, 60.0)); + let look = |copies: u64| { + let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect(); + Node::group(NodeId(2), drawn) + }; + assert!(draws_look_outline(&object, &appearance, &look(2))); + let started = std::time::Instant::now(); + assert!(!draws_look_outline(&object, &appearance, &look(5_000))); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + } + + /// The outline check holds for every point of the outlines, not only the points it checks: a + /// 0.25 pt line whose look has only short pieces over its ends, 0.24 pt away, leaves the + /// line's middle about 0.27 pt from the look, so the drawn look stays. The line drawn 0.1 pt + /// away matches. + #[test] + fn the_outline_check_holds_between_the_points_it_checks() { + use kurbo::Point; + use vectorcraft_geom::{PathData, SubPath}; + let appearance = Appearance::basic(Paint::None, Paint::None, 0.0); + let line = PathData::new(vec![SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.25, 0.0)], false)]); + let object = Node::path(NodeId(1), line, appearance.clone()); + let look = |pieces: &[[Point; 2]]| { + let drawn = PathData::new(pieces.iter().map(|p| SubPath::polyline(p, false)).collect()); + Node::group(NodeId(2), vec![Arc::new(Node::path(NodeId(3), drawn, Appearance::default()))]) + }; + let ends = [[Point::new(0.0, 0.24), Point::new(0.01, 0.24)], [Point::new(0.24, 0.24), Point::new(0.25, 0.24)]]; + assert!(!draws_look_outline(&object, &appearance, &look(&ends))); + assert!(draws_look_outline(&object, &appearance, &look(&[[Point::new(0.0, 0.1), Point::new(0.25, 0.1)]]))); + } + /// An image draws no stroke, so an image with a brush in its art style keeps its drawn look. #[test] fn an_image_with_a_brush_keeps_its_drawn_look() { diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 0d87028ec0..6215c70a6c 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -188,10 +188,11 @@ pub(super) struct ArtStyle { /// It would be [`Self::simple`] but for a Stroke Style filter's variable width written as one /// centered array ([`centered_widths`]): an object whose drawn look is empty takes it with its profile. pub uneven: bool, - /// It is several fills and strokes in solid colours or gradients (strokes without a brush), - /// each with its own visibility, opacity and blend mode but no effects of its own, under only - /// the effects any object takes that don't move the outline: what a path or compound path is - /// read with when each gradient is placed as its drawn look has it (`read::ops`' `styled`). + /// It is several fills and strokes in solid colours, gradients or patterns (strokes without a + /// brush), each with its own visibility, opacity and blend mode but no effects of its own, under + /// only the effects any object takes that don't move the outline, and under none when a pattern + /// paints: what a path or compound path is read with when each gradient and pattern is placed as + /// its drawn look has it (`read::ops`' `styled`). pub stacked: bool, /// It is one Warp on the whole object, under fills and strokes that paint nothing and have no /// effects of their own: what an image is read with when its live warp draws as its drawn look @@ -1469,11 +1470,10 @@ fn stroke_item(f: &Filter, align: StrokeAlign) -> Result, ()> if !f.paints.0 { return Ok(None); } - // Dashes aligned to corners and path ends draw as the look's pieces: a solid end at each end - // and the pattern, fitted, between them. - if f.params.get("BSDashAdj").is_some_and(|v| *v != 0.0) { - return Err(()); - } + // Dashes aligned to corners and path ends (the switch in the stroke's dictionary): the look + // draws them fitted between solid ends, which the reader checks the stroke against before it + // takes it. + let aligned = f.params.get("BSDashAdj").is_some_and(|v| *v != 0.0); match &f.stroke { Some(p) if !f.gradient && f.pattern.is_none() => Ok(Some(StyleItem::Stroke { paint: p.clone(), @@ -1481,7 +1481,7 @@ fn stroke_item(f: &Filter, align: StrokeAlign) -> Result, ()> cap: f.cap, join: f.join, miter: f.miter, - dash: f.dash.clone(), + dash: f.dash.clone().map(|d| Dash { align_corners: aligned, ..d }), profile: width_profile(&f.arrays), align, brush: None, @@ -1744,8 +1744,9 @@ impl Builder<'_> { /// Is `e`, on the whole object, an effect any object is read with? Of the Distort & Transform /// effects: Transform without copies (Random is never read), Twist, a Tweak that moves nothing, -/// Pucker & Bloat at 0, and Free Distort when its corners make a parallelogram (an affine map). -/// Zig Zag is left to type. Which objects Transform, Twist and Free Distort are read on is +/// Pucker & Bloat at 0, Free Distort when its corners make a parallelogram (an affine map), and Zig +/// Zag (on objects other than type only where it draws its drawn look's outline: `read::ops`' +/// `styled`). Which objects Transform, Twist and Free Distort are read on is /// `read::ops`' `moves_with`. fn any_object_takes(e: &Effect) -> bool { match e.id.as_str() { @@ -1762,7 +1763,8 @@ fn any_object_takes(e: &Effect) -> bool { | "path.outlineObject" | "path.outlineStroke" | "distort.twist" - | "distort.tweak" => true, + | "distort.tweak" + | "distort.zigZag" => true, // Copies are drawn as one path, its fills under all its strokes, where the file paints each // copy's fill and stroke in turn. "distort.transform" => e.params["copies"].as_i64() == Some(0), @@ -1861,9 +1863,15 @@ fn style(filters: &[Filter]) -> ArtStyle { && st.plain && !st.pathfinder && !st.moves_outline() - && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Stroke { brush: None, .. })) + && st.items.iter().all(|i| { + matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Pattern { .. } | StyleItem::Stroke { brush: None, .. }) + }) && st.looks.iter().all(|l| l.effects.is_empty()) - && st.effects.iter().all(any_object_takes); + && st.effects.iter().all(any_object_takes) + // A pattern fill under the object's effects keeps the drawn look, a conservative rule: in + // one file a Scribble over a pattern fill drew unlike its look, its tiles placed as the + // look's are (why isn't established). + && (st.effects.is_empty() || !st.items.iter().any(|i| matches!(i, StyleItem::Pattern { .. }))); st.image_warp = st.plain && matches!(st.effects.as_slice(), [e] if e.id.starts_with("warp.")) && st.items.iter().all(|i| matches!(i, StyleItem::Fill(p) | StyleItem::Stroke { paint: p, .. } if p.is_none())) diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 2b48fd268b..066473d43e 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -61,13 +61,17 @@ fn a_uniform_or_unreadable_width_profile_stays_a_live_stroke() { } #[test] -fn dashes_aligned_to_corners_keep_the_drawn_look() { - // GUARDS: the look holds the fitted pattern and the solid ends the style's dash array doesn't. +fn dashes_aligned_to_corners_read_as_aligned_dashes() { + // The look holds the fitted pattern, which the style's dash array doesn't: the reader takes the + // stroke only where VectorCraft's own fitting draws as that look. let data = b"/KnownStyle :\n(Stitches) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ /Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n\ /StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n1 J 0 j 2 w 10 M [5 10 ]0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n"; - assert!(!art_styles(data)["Stitches"].plain); + let style = &art_styles(data)["Stitches"]; + assert!(style.plain, "{style:?}"); + let [StyleItem::Stroke { dash: Some(dash), .. }] = style.items.as_slice() else { panic!("{:?}", style.items) }; + assert_eq!((dash.pattern.as_slice(), dash.align_corners), ([5.0, 10.0].as_slice(), true)); } /// The style `Shade`: a Drop Shadow whose dictionary holds `keys`. @@ -1023,7 +1027,8 @@ fn any_object_takes_the_distort_effects_that_draw_as_its_drawn_look() { assert!(simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.0], [0.0, -1.0], [1.0, -1.0]]))); assert!(!simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.1], [0.0, -1.0], [1.0, -1.0]]))); assert!(!simple("Adobe Punk and Bloat", "-35 /Real (d_factor) ,\n")); - assert!(!simple("Adobe Zigzag", "")); + // Zig Zag: objects other than type check it against their drawn look (`read::ops`). + assert!(simple("Adobe Zigzag", "")); assert!(!simple("Adobe Transform", &format!("1 /Int (numCopies) ,\n{SWITCHES}"))); // With another effect, only type takes it. let chain = [basic("Adobe Twirl", "45 /Real (angle) ,\n"), basic("Adobe Offset Path", "4 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n")]; diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index f9ed3601d2..ab7165c7a1 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1260,6 +1260,191 @@ fn a_style_pattern_fill_is_placed_as_a_direct_one() { } } +/// An art style `Stacked` whose stack holds `filters` (basic filters, top first). +fn stacked_style(filters: &[String]) -> String { + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Stacked) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{}\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n", + filters.concat() + ) +} + +/// A fill filter painting with `paint` (operators). +fn fill_filter(paint: &str) -> String { + format!( + "/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{paint}\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n" + ) +} + +/// A black stroke filter `width` wide. +fn stroke_filter(width: f64) -> String { + format!( + "/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n" + ) +} + +/// The layers of a file whose object (`own`, on `%_` lines) has the style `Stacked` and the drawn +/// look `look`. +fn stacked_object(look: &str, own: &str) -> String { + let own: String = own.lines().map(|l| format!("%_{l}\n")).collect(); + layer(&format!("0 Ae\nu\n{look}U\n{own}1 (Stacked) XW\n")) +} + +/// The pattern placement of `n`'s fill painting with a pattern. +fn pattern_xf(n: &Node) -> [f64; 6] { + n.appearance + .items + .iter() + .find_map(|i| match i.paint() { + Paint::Pattern { xf, .. } => Some(xf.as_coeffs()), + _ => None, + }) + .unwrap_or_else(|| panic!("no pattern fill: {:?}", n.appearance.items)) +} + +/// A path or compound path whose art style fills it with a pattern (as a stack of fills and strokes +/// can) comes in as itself with that fill, the pattern placed where the drawn look places it (not +/// where the style's own operands would), among the style's other fills and strokes in their order. +#[test] +fn a_path_with_a_style_pattern_fill_comes_in_as_the_path_with_it() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let hole = rect_path(30.0, 40.0, 50.0, 60.0); + // The style's operands and the look's differ: the look's placement is taken. + let (style_ops, look_ops) = ("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]", "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]"); + let pattern = fill_filter(&format!("(Dots) {style_ops} p")); + let look_xf = |shape: &str| { + let direct = read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {look_ops} p\n{shape}f\n")))); + pattern_xf(&art(&direct.doc)[0]) + }; + let close = |a: [f64; 6], b: [f64; 6]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9); + // The style's operands alone would place it elsewhere. + let style_xf = pattern_xf(&art(&read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {style_ops} p\n{rect}f\n")))).doc)[0]); + assert!(!close(style_xf, look_xf(&rect)), "{style_xf:?}"); + // A path filled with the pattern alone. + let look = format!("(Dots) {look_ops} p\n{rect}f\n"); + let r = read_ok(&format!("{}{DOTS}{}", stacked_style(std::slice::from_ref(&pattern)), stacked_object(&look, &format!("{rect}n")))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Path { .. })), "the path: {a:#?} {:?}", r.warnings); + assert!(close(pattern_xf(&a[0]), look_xf(&rect)), "{:?} {:?}", pattern_xf(&a[0]), look_xf(&rect)); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + // A compound path, the pattern over a solid fill and under a 3 unit stroke. + let style = stacked_style(&[stroke_filter(3.0), pattern.clone(), fill_filter("0 1 1 0 1 0 0 Xa")]); + let look = format!("{RED}*u\n{rect}f\n{hole}f\n*U\n(Dots) {look_ops} p\n*u\n{rect}f\n{hole}f\n*U\n"); + let own = format!("*u\n{rect}n\n{hole}n\n*U"); + let r = read_ok(&format!("{style}{DOTS}{}", stacked_object(&look, &own))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Compound { .. })), "the compound path: {a:#?} {:?}", r.warnings); + let items: Vec = a[0] + .appearance + .items + .iter() + .map(|i| match (i, i.paint()) { + (AppearanceItem::Fill(_), Paint::Pattern { .. }) => "pattern fill".into(), + (AppearanceItem::Fill(_), p) => format!("fill {:?}", p.color()), + (AppearanceItem::Stroke(s), _) => format!("stroke {}", s.width), + }) + .collect(); + assert_eq!(items, [format!("fill {:?}", Some(Color::rgb(1.0, 0.0, 0.0))), "pattern fill".into(), "stroke 3".into()]); + assert!(close(pattern_xf(&a[0]), look_xf(&format!("*u\n{rect}f\n{hole}f\n*U\n")))); +} + +/// A stack's pattern fill keeps the drawn look where the look doesn't fill with that pattern: its +/// placement isn't known. A look that only strokes with it doesn't place the fill either. +#[test] +fn a_style_pattern_fill_the_look_doesnt_paint_keeps_the_drawn_look() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let ops = "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"; + let pattern = fill_filter(&format!("(Dots) {ops} p")); + for (why, look) in + [("a look without the pattern", format!("{RED}{rect}f\n")), ("a look that strokes with it", format!("(Dots) {ops} P\n{rect}S\n"))] + { + let r = read_ok(&format!("{}{DOTS}{}", stacked_style(std::slice::from_ref(&pattern)), stacked_object(&look, &format!("{rect}n")))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "{why}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings); + } +} + +/// A stack that fills with one pattern twice keeps the drawn look: which of the look's placements is +/// whose isn't known. +#[test] +fn a_stack_with_one_pattern_twice_keeps_the_drawn_look() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let ops = "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"; + let pattern = fill_filter(&format!("(Dots) {ops} p")); + let look = format!("(Dots) {ops} p\n{rect}f\n(Dots) {ops} p\n{rect}f\n"); + let r = read_ok(&format!("{}{DOTS}{}", stacked_style(&[pattern.clone(), pattern]), stacked_object(&look, &format!("{rect}n")))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +/// A stack that fills with a pattern once, whose drawn look fills with it twice at different +/// placements, keeps the drawn look: which placement is the style's isn't known. A look filling with +/// it twice at the same placement still comes in as the path with that fill. +#[test] +fn a_look_placing_a_stacks_pattern_twice_keeps_the_drawn_look() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let ops = "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"; + let other = "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]"; + let pattern = fill_filter(&format!("(Dots) {ops} p")); + let read = |second: &str| { + let look = format!("(Dots) {ops} p\n{rect}f\n(Dots) {second} p\n{rect}f\n"); + read_ok(&format!("{}{DOTS}{}", stacked_style(std::slice::from_ref(&pattern)), stacked_object(&look, &format!("{rect}n")))) + }; + let r = read(other); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let r = read(ops); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Path { .. })), "the path: {a:#?} {:?}", r.warnings); +} + +/// A style's pattern fill under an effect on the object keeps the drawn look, a conservative rule +/// (in one file a Scribble over a pattern fill drew unlike its look; why isn't established). +#[test] +fn a_path_with_a_style_pattern_fill_under_an_effect_keeps_its_drawn_look() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let hidden = rect.replace('\n', "\n%_"); + let ops = "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"; + let shadow = "/BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n2 /Int (blnd) ,\n0.43 /Real (opac) ,\n\ + 37 /Real (dark) ,\n-13 /Real (vert) ,\n11 /Real (horz) ,\n17 /Real (blur) ,\n\ + /FillStyle : 0 O\n0 0 0 0 0 1 0 Xa\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Def ;\n (sclr) ,\n0 /Int (csrc) ,\n; /Dict ;\n /Part ,\n"; + let style = tiled_style("Dots", ops); + // After the stack, in the object's chain. + let end = ";\n /Part ,\n;\n%AI9_EndArtStyles"; + assert!(style.contains(end)); + let style = style.replace(end, &format!(";\n /Part ,\n{shadow};\n%AI9_EndArtStyles")); + // The style reads, with its pattern fill and the shadow: what keeps the look is the rule. + let st = crate::import::ai::style::art_styles(style.as_bytes()); + let tiled = &st["Tiled"]; + assert!(tiled.plain && tiled.effects.len() == 1, "{tiled:?}"); + let look = format!("0 Ae\nu\n(Dots) {ops} p\n{rect}f\nU\n"); + let r = read_ok(&format!("{style}{DOTS}{}", layer(&format!("{look}%_{hidden}n\n1 (Tiled) XW\n")))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +/// Type whose style fills it with a pattern takes the placement from its drawn look wherever the look +/// paints with that pattern, a stroke of it too (as before paths took such styles): the look's +/// fills-only rule is the path stack's. +#[test] +fn type_with_a_style_pattern_fill_takes_a_stroke_only_looks_placement() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let (style_ops, look_ops) = ("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]", "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]"); + let look = format!("0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n(Dots) {look_ops} P\n{rect}S\nU\n"); + let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n"; + let styled = read_ok(&format!("{}{DOTS}{}", tiled_style("Dots", style_ops), layer(&format!("{look}{own}1 (Tiled) XW\n")))); + let stroked = read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {look_ops} P\n{rect}S\n")))); + let Paint::Pattern { xf: got, .. } = fill(&art(&styled.doc)[0]) else { panic!("{:?} {:?}", art(&styled.doc), styled.warnings) }; + let want = pattern_xf(&art(&stroked.doc)[0]); + assert!(got.as_coeffs().iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{got:?} {want:?}"); +} + /// An art style's pattern fill paints with the pattern under the name it is shown with. #[test] fn a_style_pattern_fill_paints_with_the_shown_name() { @@ -1549,6 +1734,42 @@ fn a_clipping_path_alone_in_a_group_clips_its_clipping_group() { assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); } +/// Clipping paths grouped in a compound path (`*u u W n … U *U`, possibly nested in other groups) are +/// the compound path's subpaths, as its other grouped paths are: the compound clipping path, their union, clips its +/// clipping group, however many there are and wherever in the group it is written. +#[test] +fn clipping_paths_grouped_in_a_compound_path_are_its_subpaths() { + let square = rect_path(0.0, 0.0, 80.0, 80.0); + let (a, b, c) = (rect_path(0.0, 0.0, 10.0, 10.0), rect_path(30.0, 0.0, 40.0, 10.0), rect_path(60.0, 0.0, 70.0, 10.0)); + let clip = |p: &str| format!("{p}h\nW\nn\n"); + let bodies = [ + // One group of them, after the art. + format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}{}{}U\n*U\nQ\n", clip(&a), clip(&b), clip(&c)), + // Groups in a group, and one path straight in the compound path, before the art. + format!("0 Ae\nq\n*u\n0 Ae\nu\n0 Ae\nu\n{}{}U\n0 Ae\nu\n{}U\nU\n*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)), + format!("0 Ae\nq\n*u\n0 Ae\nu\n{}{}U\n{}*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)), + ]; + for body in &bodies { + let doc = read_ok(&layer(body)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{body}: {:?}", art(&doc)[0].kind) }; + assert_eq!(children.len(), 2, "{body}: {children:?}"); + let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{body}: {:?}", children[0].kind) }; + assert_eq!(subpaths.len(), 3, "{body}: {subpaths:?}"); + assert!(subpaths.iter().all(|p| matches!(p.kind, NodeKind::Path { clipping: true, .. })), "{body}: {subpaths:?}"); + assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "{body}"); + } + // Hundreds of them, one union: not clipping groups nested past the document's depth limit. + let many = format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}U\n*U\nQ\n", clip(&a).repeat(300)); + let doc = read_ok(&layer(&many)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + assert_eq!(subpaths.len(), 300); + // A group of clipping paths outside a compound path or a clipping group is read as before: a clipping group. + let alone = format!("0 Ae\nu\n{}{}U\n{RED}{square}f\n", clip(&a), clip(&b)); + let doc = read_ok(&layer(&alone)).doc; + assert!(matches!(art(&doc)[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", art(&doc)[0].kind); +} + /// #1410: a compound path shows its last path's paint, and paths grouped in it stay its paths. #[test] fn compound_path_takes_its_last_paths_paint() { @@ -2507,6 +2728,37 @@ fn ai_variable_library_edge_cases() { assert_eq!(notes, ["the file's variable library couldn't be read: the Variables panel doesn't list it"]); } +/// The empty library a file can keep, its nodes named and nothing else (no value, no type, empty +/// attributes), has nothing to list: it comes in without a note. A node that has a value or a type +/// isn't empty, so the same skeleton with a value, or with a type, still gets the note. +#[test] +fn an_empty_variable_library_gives_no_note() { + // A node with a name and nothing else: its children, then its attributes, as `%_` lines. + fn bare(name: &str, attributes: &[&str], children: &[String]) -> String { + let close = |n: &str, key: &str| format!("{}%_; {key},\n", n.strip_suffix("%_;\n").unwrap_or(n)); + let attributes: String = attributes.iter().map(|a| close(&bare(a, &[], &[]), &format!("({a}) "))).collect(); + let children: String = children.iter().map(|c| close(c, "")).collect(); + format!( + "%_/XMLNode :\n%_/Dictionary :\n{attributes}%_; (xmlnode-attributes) ,\n%_/Array :\n{children}%_; (xmlnode-children) ,\n%_({name}) /String (xmlnode-nodename) ,\n%_;\n" + ) + } + let data_sets = bare("v:sampleDataSets", &["xmlns:v", "xmlns"], &[]); + let skeleton = bare("variableSets", &[], &[bare("variableSet", &["varSetName"], std::slice::from_ref(&data_sets))]); + let (vars, notes) = read_library(&skeleton); + assert_eq!(vars, vectorcraft_doc::Variables::default()); + assert!(notes.is_empty(), "{notes:?}"); + let unread = ["the file's variable library couldn't be read: the Variables panel doesn't list it"]; + // The same skeleton but for one entry of the data sets node: a value, then a type. + let with = |entry: &str| { + let data_sets = data_sets.replace("(xmlnode-nodename) ,\n", &format!("(xmlnode-nodename) ,\n{entry}")); + bare("variableSets", &[], &[bare("variableSet", &["varSetName"], &[data_sets])]) + }; + for entry in ["%_(x) /String (xmlnode-nodevalue) ,\n", "%_1 /Int (xmlnode-nodetype) ,\n"] { + let (_, notes) = read_library(&with(entry)); + assert_eq!(notes, unread, "{entry}"); + } +} + /// When the layers can't be read, or reading stops before the library, [`variables`] still reads /// it, for the file read from its PDF part. #[test] @@ -3741,6 +3993,70 @@ fn placed_files_are_linked_images_showing_their_preview() { assert!(read(stream(&layer("~\n")).as_bytes()).unwrap_err().contains("`~`")); } +/// Type made a clipping mask: a clipping group (`q` … `Q`) with no clipping path, whose last object +/// is a text object, is clipped by that type once its slot holds it, the type first as its +/// clipping path. Anything else stays as it was read. +#[test] +fn type_that_ends_a_clipping_group_without_a_clipping_path_clips_it() { + let text = |story: u32| format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n;\n"); + let square = format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let clipper = format!("{RED}{}h W n\n", rect_path(2.0, 2.0, 8.0, 8.0)); + let r = read_ok(&layer(&format!("q\n{square}{}Q\n", text(4)))); + let a = art(&r.doc); + let [group] = a.as_slice() else { panic!("{a:#?}") }; + let slot = group.children().and_then(|c| c.last()).map(|n| n.id).unwrap(); + assert!(matches!(group.kind, NodeKind::Group { clip: false, .. }), "read as it is, until the slot holds its type"); + assert_eq!(r.type_clips.get(&group.id), Some(&slot)); + assert_eq!(r.warped_type.type_clips, r.type_clips, "envelopes' contents are clipped by their type too"); + // Filled with one text object, the slot's type clips the group. + let typed = |doc: &Document, one: bool| { + let mut layer = (*doc.layers[0]).clone(); + let mut n = 0; + let put = |n: &mut Node| { + if let NodeKind::Group { children, .. } = &mut n.kind + && let Some(last) = children.last_mut() + && last.id == slot + { + let t = Node::new( + vectorcraft_doc::NodeId(9_000), + NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(kurbo::Point::ZERO, "M", Default::default()))), + ); + if one { + *last = Arc::new(t); + } else { + let mut stroke = t.clone(); + stroke.id = vectorcraft_doc::NodeId(9_001); + *last = Arc::new(t); + children.push(Arc::new(stroke)); + } + } + }; + layer.children_mut().unwrap().iter_mut().for_each(|c| put(Arc::make_mut(c))); + let clipped = clip_by_type(&mut layer, &r.type_clips, &|s| (s == slot).then_some(vectorcraft_doc::NodeId(9_000)), &mut |_| n += 1); + (layer, clipped, n) + }; + let (layer_one, clipped, called) = typed(&r.doc, true); + assert_eq!((clipped, called), (1, 1)); + let g = &layer_one.children().unwrap()[0]; + let NodeKind::Group { children, clip: true } = &g.kind else { panic!("{g:#?}") }; + assert!(matches!(children[0].kind, NodeKind::Text(_)) && matches!(children[1].kind, NodeKind::Path { .. }), "{children:#?}"); + // Several objects in its place (the type and strokes round it): the group stays unclipped. + let (layer_two, clipped, _) = typed(&r.doc, false); + assert_eq!(clipped, 0); + assert!(matches!(layer_two.children().unwrap()[0].kind, NodeKind::Group { clip: false, .. })); + // A clipping path in the group clips it, not the type; type that isn't last doesn't; nor does a + // group (`u` … `U`) or the type a look draws. + for body in [ + format!("q\n{square}{clipper}{}Q\n", text(4)), + format!("q\n{}{square}Q\n", text(4)), + format!("u\n{square}{}U\n", text(4)), + format!("q\n{square}/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nQ\n"), + ] { + let r = read_ok(&layer(&body)); + assert!(r.type_clips.is_empty(), "{body}: {:?}", r.type_clips); + } +} + #[test] fn text_objects_are_slots_named_after_their_story() { let words = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n3 /StoryIndex ,\n;\n%_/ArtDictionary :\n%_/XMLUID : (Title) ; (AI10_ArtUID) ,\n%_;\n"; @@ -6272,21 +6588,13 @@ fn a_stroke_offset_filter_keeps_its_strokes_style() { } /// A Stroke Offset stroke this doesn't read as a stroke keeps the object's drawn look: a switch -/// written as another kind, dashes aligned to corners and path ends, a gradient. +/// written as another kind, a gradient. #[test] fn a_stroke_offset_filter_with_a_stroke_this_does_not_read_keeps_the_drawn_look() { let outside = "0 /Bool (StrokeOffsetInside) ,\n"; let gradient = "0 R\nBb\n0 0 0 0 Bh\n2 (Red ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd"; let cases = [ ("a switch written as a number", offset_stroke_style_with("Edge", "1 /Int (StrokeOffsetInside) ,\n", OFFSET_STROKE)), - ( - "dashes aligned to corners", - offset_stroke_style_with( - "Edge", - &format!("{outside}/Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n"), - &OFFSET_STROKE.replace("[]0 d", "[5 10 ]0 d"), - ), - ), ("a gradient", offset_stroke_style_with("Edge", outside, gradient)), ]; for (why, style) in cases { @@ -6295,6 +6603,26 @@ fn a_stroke_offset_filter_with_a_stroke_this_does_not_read_keeps_the_drawn_look( } } +/// A Stroke Offset stroke with dashes aligned to corners and path ends reads as such a stroke, +/// outside the path; the object takes it only where it draws as its drawn look. Here the look (a +/// filled square) draws otherwise, so the look check keeps the drawn look. +#[test] +fn a_stroke_offset_with_dashes_aligned_to_corners_unlike_its_look_keeps_the_look() { + use crate::import::ai::style::StyleItem; + use vectorcraft_doc::StrokeAlign; + let keys = "0 /Bool (StrokeOffsetInside) ,\n/Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n"; + let style = offset_stroke_style_with("Edge", keys, &OFFSET_STROKE.replace("[]0 d", "[5 10 ]0 d")); + let styles = crate::import::ai::style::art_styles(style.as_bytes()); + let Some(StyleItem::Stroke { dash: Some(dash), align, .. }) = styles["Edge"].items.iter().find(|i| matches!(i, StyleItem::Stroke { .. })) else { + panic!("{:?}", styles["Edge"]) + }; + assert_eq!((dash.pattern.as_slice(), dash.align_corners, *align), ([5.0, 10.0].as_slice(), true, StrokeAlign::Outside)); + let r = read_ok(&format!("%AI9_BeginArtStyles\n{style}%AI9_EndArtStyles\n{}", layer(&styled_square("Edge")))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "the drawn look: {a:#?}"); +} + /// A listed `[Default]` style whose stroke is aligned outside comes in as the default graphic /// style with that stroke. #[test] @@ -7338,6 +7666,96 @@ fn an_object_with_a_distort_effect_drawn_another_way_keeps_its_drawn_look() { } } +#[test] +fn a_path_with_zig_zag_comes_in_as_itself_where_its_look_has_that_outline() { + // GUARDS: Zig Zag on a path came in as its drawn look even where the live effect draws the same outline. + let keys = "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n2 /Real (ridges) ,\n0 /Real (roundness) ,\n"; + let zig = vectorcraft_doc::Effect { + id: "distort.zigZag".into(), + params: serde_json::json!({"size": 3.0, "relative": false, "ridges": 2, "points": "corner"}), + visible: true, + }; + // The square as the document has it (y up in the file, down in the document). + let plain = read_ok(&layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 60.0, 50.0)))); + let square = art(&plain.doc)[0].path_data().unwrap().clone(); + let to_file = |p: Point| { + let start = square.subpaths[0].anchors[0].p; + Point::new(p.x - start.x + 20.0, start.y - p.y + 20.0) + }; + let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &square, square.bounds().unwrap()); + // The look: the outline the effect draws, as straight segments. + let ops = |shift: f64| -> String { + let mut out = String::new(); + for sp in &outline.subpaths { + for (i, a) in sp.anchors.iter().enumerate() { + let p = to_file(a.p); + out.push_str(&format!("{:.4} {:.4} {}\n", p.x + shift, p.y, if i == 0 { "m" } else { "L" })); + } + } + out + }; + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}f\nU\n%_{hidden_rect}f\n1 (Bent) XW\n"); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(0.0))))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}"); + let e = &a[0].appearance.effects; + assert_eq!(e.len(), 1, "{e:?}"); + assert_eq!( + (e[0].id.as_str(), &e[0].params), + ("distort.zigZag", &serde_json::json!({"size": 3.0, "relative": false, "ridges": 2, "points": "corner"})) + ); + // A look whose ridges lie elsewhere (here 1 pt to the right) keeps the drawn look. + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(1.0))))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + assert!(matches!(art(&r.doc)[0].kind, NodeKind::Group { .. })); + // An open path (filled without closing it, `F`): its look's outline matches, and a look whose + // last point lies 3 pt away from where the effect ends it keeps the drawn look. + let open_path = "20 20 m\n60 20 L\n60 50 L\n"; + let plain = read_ok(&layer(&format!("{RED}{open_path}F\n"))); + let open = art(&plain.doc)[0].path_data().unwrap().clone(); + assert!(!open.subpaths[0].closed); + let start = open.subpaths[0].anchors[0].p; + let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &open, open.bounds().unwrap()); + let ops = |last_shift: f64| -> String { + let mut out = String::new(); + for sp in &outline.subpaths { + for (i, a) in sp.anchors.iter().enumerate() { + let shift = if i + 1 == sp.anchors.len() { last_shift } else { 0.0 }; + let p = Point::new(a.p.x - start.x + 20.0 + shift, start.y - a.p.y + 20.0); + out.push_str(&format!("{:.4} {:.4} {}\n", p.x, p.y, if i == 0 { "m" } else { "L" })); + } + } + out + }; + let hidden_open = open_path.replace('\n', "\n%_"); + let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}F\nU\n%_{hidden_open}F\n1 (Bent) XW\n"); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(0.0))))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(3.0))))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + // A Zig Zag of no size on an open path through the corners of its look's square, joined + // across it: the vertices match, the segments between them don't, so the drawn look stays. + let flat = "0 /Real (amount) ,\n1 /Real (absoluteness) ,\n0 /Real (ridges) ,\n0 /Real (roundness) ,\n"; + let bowtie = "%_20 20 m\n%_60 50 L\n%_60 20 L\n%_20 50 L\n%_F\n"; + let crossed = format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{}f\nU\n{bowtie}1 (Bent) XW\n", rect_path(20.0, 20.0, 60.0, 50.0)); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", flat, BLUE_FILL), layer(&crossed))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + // A look worked out by hand rather than by the effect: Zig Zag of 3 pt with one ridge per + // segment and corner points, on a line from (20, 20) to (60, 20), puts the line's ends 3 pt up + // the page and its middle 3 pt down. The same look mirrored keeps the drawn look. + let one = "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n1 /Real (ridges) ,\n0 /Real (roundness) ,\n"; + let line = "20 20 m\n60 20 L\n".replace('\n', "\n%_"); + let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}F\nU\n%_{line}F\n1 (Bent) XW\n"); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", one, BLUE_FILL), layer(&object("20 23 m\n40 17 L\n60 23 L\n")))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + assert!(matches!(art(&r.doc)[0].kind, NodeKind::Path { .. }), "{:#?}", art(&r.doc)); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", one, BLUE_FILL), layer(&object("20 17 m\n40 23 L\n60 17 L\n")))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + /// The gradient `G`, white to black, defined for a document. const GRADIENT_G: &str = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; @@ -8746,7 +9164,7 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); let settle = |w: &super::envelope::WarpedLook, spent| { - let warped = super::envelope::WarpedType { looks: vec![copy(w)], envelopes: vec![], checks: 1, spent, page, alone: None }; + let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page, ..Default::default() }; warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) }; let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; @@ -9519,6 +9937,22 @@ fn a_blend_comes_in_as_a_live_blend() { assert!(!s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings); } +/// A blend in an opacity mask's art is written on `%_` lines, its record's hex digits on `%_%` +/// lines: it comes in live there too. +#[test] +fn a_blend_in_an_opacity_mask_comes_in_live() { + let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B'])); + let mask_art: String = body.lines().map(|l| if l.starts_with("%_") { format!("{l}\n") } else { format!("%_{l}\n") }).collect(); + assert!(mask_art.contains("\n%_%44434241"), "{mask_art}"); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n%_u\n{mask_art}%_U\n%_X+\n%_(Art) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let s = read_ok(&layer(&format!("{RED}0 0 m\n0 80 L\n80 80 L\n80 0 L\nf\n{mask}"))); + let m = art(&s.doc)[0].extras().mask.clone().expect("a mask"); + let blend = m.art.children().and_then(|c| c.first()).cloned().unwrap_or(m.art.clone()); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend: {:?} {:?}", blend.kind, s.warnings) }; + assert_eq!((children.len(), spec.spacing), (2, vectorcraft_doc::live::BlendSpacing::Steps(3))); + assert!(!s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings); +} + /// A blend whose spine was never edited has no spine written, only its keys: its spine is the /// straight line between the keys' centers, in the record's order, and the blend comes in live. /// With the record naming the keys in their order (here the left key, named `B`, first) the blend diff --git a/crates/eps/src/import/graphics/ops.rs b/crates/eps/src/import/graphics/ops.rs index 78a214b410..1afd09eae2 100644 --- a/crates/eps/src/import/graphics/ops.rs +++ b/crates/eps/src/import/graphics/ops.rs @@ -1,4 +1,4 @@ -use super::paint::is_mesh; +use super::paint::{is_mesh, polygon, shading_extent}; use super::state::{GState, Space}; use super::{ Affine, Color, FillRule, Interp, Key, LineCap, LineJoin, MAX_DASH_ENTRIES, MAX_DASHES, MAX_GSAVE, MAX_PATH, Obj, Op, Paint, Point, PsError, Rc, @@ -519,29 +519,43 @@ impl Interp<'_> { } self.stroke_path(bp)?; } - ShFill => { - let d = self.pop_dict()?; - if self.g.null { - return Ok(()); - } - if is_mesh(&d) { - let m = self.xf(); - return self.mesh_fill(&d, m); - } - let m = self.xf(); - if let Some(g) = self.gradient(&d, m)? { - let area = self.clip_bounds()?; - let paint = Paint::Gradient(Box::new(g)); - let clips = self.g.clips.clone(); - self.out.fill(area.to_path(0.1), FillRule::NonZero, paint, self.g.overprint, &clips); - if let Some((_, n)) = self.out.drawn.last() { - let id = n.id; - self.out.shadings.insert(id); - } - } - } + ShFill => self.shfill()?, _ => self.data_op(op)?, } Ok(()) } + + /// `shfill`: shading `sh` over the clip, as a gradient mesh or a gradient fill. + fn shfill(&mut self) -> Res { + let d = self.pop_dict()?; + if self.g.null { + return Ok(()); + } + if is_mesh(&d) { + let m = self.xf(); + return self.mesh_fill(&d, m); + } + let m = self.xf(); + if let Some(g) = self.gradient(&d, m)? { + let area = self.clip_bounds()?; + // Not extended, it paints only between its ends. + let extent = shading_extent(&d, m, area); + let path = match &extent { + Some(pts) if pts.len() < 3 => return Ok(()), + Some(pts) => polygon(pts), + None => area.to_path(0.1), + }; + let paint = Paint::Gradient(Box::new(g)); + let clips = self.g.clips.clone(); + self.out.fill(path, FillRule::NonZero, paint, self.g.overprint, &clips); + // Only a fill of the whole clip can stand in for the clip's shape. + if extent.is_none() + && let Some((_, n)) = self.out.drawn.last() + { + let id = n.id; + self.out.shadings.insert(id); + } + } + Ok(()) + } } diff --git a/crates/eps/src/import/graphics/paint.rs b/crates/eps/src/import/graphics/paint.rs index 156b6e421e..037cf1d213 100644 --- a/crates/eps/src/import/graphics/paint.rs +++ b/crates/eps/src/import/graphics/paint.rs @@ -450,6 +450,135 @@ fn is_gradient(sh: &DictRef) -> bool { matches!(sh.borrow().get(&Key::name("ShadingType")).and_then(Obj::as_num), Some(2.0 | 3.0)) } +/// How far (points) the sides of the polygon a radial shading's circle is cut to may lie inside it. +const RING_TOLERANCE: f64 = 0.01; +/// Most sides of that polygon. +const MAX_RING: usize = 1024; + +/// The part of `area` (in the document) that axial or radial shading `sh`, mapped into the +/// document by `m`, paints, as a convex polygon; `None` when it paints all of it. Without +/// `Extend` an axial shading paints only between the lines through its ends across its axis, and +/// a radial one only over its circles (PLRM 3rd ed. §4.9.3, shading types 2 and 3: `Extend` +/// defaults to `[false false]`). A radial shading extended at one end only, or starting from a +/// circle with a radius, is not bounded here (it paints all of `area`). +pub(super) fn shading_extent(sh: &DictRef, m: Affine, area: Rect) -> Option> { + let d = sh.borrow(); + let nums = |k: &str| -> Vec { + d.get(&Key::name(k)).and_then(Obj::items).map(|i| i.borrow().iter().filter_map(Obj::as_num).collect()).unwrap_or_default() + }; + let extend: Vec = d + .get(&Key::name("Extend")) + .and_then(Obj::items) + .map(|i| i.borrow().iter().map(|o| matches!(o, Obj::Bool(true))).collect()) + .unwrap_or_default(); + let (e0, e1) = (extend.first().copied().unwrap_or(false), extend.get(1).copied().unwrap_or(false)); + if (e0 && e1) || area.width() <= 0.0 || area.height() <= 0.0 || m.determinant().abs() < 1e-12 || !m.as_coeffs().iter().all(|v| v.is_finite()) { + return None; + } + let inv = m.inverse(); + // `area` in the shading's own space, where its axis and circles are. + let corners: Vec = + [(area.x0, area.y0), (area.x1, area.y0), (area.x1, area.y1), (area.x0, area.y1)].map(|(x, y)| inv * Point::new(x, y)).to_vec(); + let mut poly = corners.clone(); + let c = nums("Coords"); + let at = |i: usize| c.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0); + match d.get(&Key::name("ShadingType")).and_then(Obj::as_num) { + Some(2.0) => { + let (p0, p1) = (Point::new(at(0), at(1)), Point::new(at(2), at(3))); + let axis = p1 - p0; + if axis.hypot2() < 1e-18 { + return None; + } + if !e0 { + poly = clip_half(&poly, |p| (p - p0).dot(axis)); + } + if !e1 { + poly = clip_half(&poly, |p| (p1 - p).dot(axis)); + } + } + Some(3.0) if !e0 && !e1 && at(2) <= 0.0 && at(5) > 0.0 => { + // The circles from a point to a circle cover the hull of that point and circle. + let (p0, c1, r1) = (Point::new(at(0), at(1)), Point::new(at(3), at(4)), at(5)); + // Enough sides that each lies within `RING_TOLERANCE` of the circle in the document + // (the radius scaled by the most `m` stretches any direction), from 64 to `MAX_RING`. + let [a, b, c, d, ..] = m.as_coeffs(); + let (sum, det) = (a * a + b * b + c * c + d * d, a * d - b * c); + let stretch = ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt(); + let r = r1 * stretch; + let sides = (std::f64::consts::PI / (1.0 - RING_TOLERANCE / r).clamp(-1.0, 1.0).acos()).ceil(); + let sides = if sides.is_finite() { (sides as usize).clamp(64, MAX_RING) } else { MAX_RING }; + let ring: Vec = (0..sides).map(|i| c1 + Vec2::from_angle(i as f64 * std::f64::consts::TAU / sides as f64) * r1).collect(); + for edge in hull(&[ring, vec![p0]].concat()).windows(2) { + if let [a, b] = edge { + let (a, b) = (*a, *b); + poly = clip_half(&poly, |p| (b - a).cross(p - a)); + } + } + } + _ => return None, + } + // Nothing cut: it paints the whole area. + if poly.len() == 4 && poly.iter().zip(&corners).all(|(a, b)| (*a - *b).hypot2() < 1e-18) { + return None; + } + Some(poly.into_iter().map(|p| m * p).collect()) +} + +/// Convex polygon `poly` cut to where `f` (a linear function) is zero or more. +fn clip_half(poly: &[Point], f: impl Fn(Point) -> f64) -> Vec { + let mut out = Vec::with_capacity(poly.len() + 1); + for (i, &a) in poly.iter().enumerate() { + let Some(&b) = poly.get((i + 1) % poly.len()) else { continue }; + let (fa, fb) = (f(a), f(b)); + if fa >= 0.0 { + out.push(a); + } + if (fa >= 0.0) != (fb >= 0.0) { + out.push(a.lerp(b, fa / (fa - fb))); + } + } + out +} + +/// The convex hull of `pts`, counter-clockwise, its first point repeated at the end. +fn hull(pts: &[Point]) -> Vec { + let mut p = pts.to_vec(); + p.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + let mut h: Vec = Vec::with_capacity(p.len() * 2); + let turn = |h: &[Point], q: Point| match h { + [.., a, b] => (*b - *a).cross(q - *a) <= 0.0, + _ => false, + }; + for &q in &p { + while turn(&h, q) { + h.pop(); + } + h.push(q); + } + let lower = h.len() + 1; + for &q in p.iter().rev().skip(1) { + while h.len() >= lower && turn(&h, q) { + h.pop(); + } + h.push(q); + } + h +} + +/// A closed path through `pts`. +pub(super) fn polygon(pts: &[Point]) -> kurbo::BezPath { + let mut bp = kurbo::BezPath::new(); + for (i, p) in pts.iter().enumerate() { + if i == 0 { + bp.move_to(*p); + } else { + bp.line_to(*p); + } + } + bp.close_path(); + bp +} + /// Is shading `sh` one [`Interp::mesh_fill`] paints? pub(super) fn is_mesh(sh: &DictRef) -> bool { matches!(sh.borrow().get(&Key::name("ShadingType")).and_then(Obj::as_num), Some(1.0 | 4.0 | 5.0 | 6.0 | 7.0)) diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 86d6976d89..5a2282f807 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -329,6 +329,7 @@ pub(super) fn build_weighing( unread, unread_elsewhere, slot_names, + type_clips, restyled, placeholders, placed_elsewhere, @@ -527,6 +528,7 @@ pub(super) fn build_weighing( let mut made = vec![]; let mut filled = std::collections::HashMap::new(); fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty, &mut made, &mut vec![], &mut filled); + clip_by_type(&mut layers, &type_clips, &filled); doc.layers = layers; made.sort(); let threaded_frames: BTreeSet = @@ -2155,6 +2157,30 @@ fn unmark(nodes: &mut [Arc], shown: bool, prints: bool, found: &mut Vec<(N } } +/// Make the clipping groups in `layers` that their type clips ([`Structure::type_clips`]) clip by it, +/// where its slot became one text object (`filled`). The page shows that type by what it clips, so +/// it is never weighed as type the page doesn't draw ([`prune_unseen`]). +fn clip_by_type( + layers: &mut [Arc], + type_clips: &std::collections::HashMap, + filled: &std::collections::HashMap, +) { + let one = |slot: NodeId| { + filled.get(&slot).and_then(|f| match f.objects.as_slice() { + [id] => Some(*id), + _ => None, + }) + }; + let mut seen = |n: &mut Node| { + if let Some(name) = n.name.as_deref().and_then(|m| m.strip_prefix(MADE)) { + n.name = (!name.is_empty()).then(|| name.to_string()); + } + }; + for l in layers { + ai::clip_by_type(Arc::make_mut(l), type_clips, &one, &mut seen); + } +} + /// Take object `id` out of `nodes` (`hide`: leave it, hidden); whether it was there. fn take_out(nodes: &mut Vec>, id: NodeId, hide: bool) -> bool { if let Some(i) = nodes.iter().position(|n| n.id == id) { diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index 270a1a3aa4..63859b3e52 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -1180,6 +1180,96 @@ fn filter_output_counts_against_the_memory_budget() { assert!(err.contains("too much memory"), "{err}"); } +/// A shading painted with `shfill` and not extended paints only between its ends: an axial one +/// between the lines through them across its axis, a radial one from a point over its circles +/// (PLRM 3rd ed. §4.9.3: `Extend` is `[false false]` by default). Extended both ways it paints +/// the whole clip. +#[test] +fn shadings_not_extended_paint_only_between_their_ends() { + let shade = |kind: u8, coords: &str, extend: &str| { + let r = read(&format!( + "<< /ShadingType {kind} /ColorSpace /DeviceRGB /Coords [{coords}] {extend} \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill" + )); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + bounds(&n) + }; + // Axial, from x 10 to 90 (and its reflection in y: the document's y runs down). + let b = shade(2, "10 0 90 0", ""); + assert!(near(b, Rect::new(10.0, 0.0, 90.0, 100.0)), "{b:?}"); + let b = shade(2, "10 0 90 0", "/Extend [false true]"); + assert!(near(b, Rect::new(10.0, 0.0, 100.0, 100.0)), "{b:?}"); + let b = shade(2, "10 0 90 0", "/Extend [true true]"); + assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{b:?}"); + // Radial from the centre point to a circle of radius 30. + let b = shade(3, "50 50 0 50 50 30", ""); + assert!((b.width() - 60.0).abs() < 0.5 && (b.height() - 60.0).abs() < 0.5 && (b.center().x - 50.0).abs() < 0.5, "{b:?}"); + // Its circle is cut to a polygon whose sides lie within 0.01 pt of it, also for a large one. + let r = read( + "<< /ShadingType 3 /ColorSpace /DeviceRGB /Coords [50 50 0 50 50 45] \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill", + ); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") }; + let ring: Vec = path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect(); + let centre = Point::new(50.0, 50.0); + for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)) { + assert!((a.distance(centre) - 45.0).abs() < 1e-6, "{a:?}"); + assert!(a.midpoint(*b).distance(centre) > 45.0 - 0.01, "{a:?} {b:?}"); + } + // Stretched 4 times across and squashed to a quarter down (areas unchanged), the sides still + // lie within 0.01 pt of the ellipse it becomes. + let r = read( + "50 50 translate 4 0.25 scale << /ShadingType 3 /ColorSpace /DeviceRGB /Coords [0 0 0 0 0 10] \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill", + ); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") }; + let sides = path.subpaths.iter().map(|s| s.anchors.len()).sum::(); + // A side of a regular polygon in the circle lies 1 - cos(pi / sides) of the radius inside it; + // stretched to 40 pt across, that is at most 0.01 pt. + assert!(40.0 * (1.0 - (std::f64::consts::PI / sides as f64).cos()) <= 0.01 + 1e-9, "{sides} sides"); + let b = shade(3, "50 50 0 50 50 30", "/Extend [true true]"); + assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{b:?}"); + + // Axial along y, and extended at its start only. + let b = shade(2, "0 20 0 70", ""); + assert!(near(b, Rect::new(0.0, 30.0, 100.0, 80.0)), "{b:?}"); + let b = shade(2, "10 0 90 0", "/Extend [true false]"); + assert!(near(b, Rect::new(0.0, 0.0, 90.0, 100.0)), "{b:?}"); + // Diagonal: from (60, 60) to (90, 90) it paints where x + y lies from 120 to 180, a strip + // across the square's top-right corner whose own corners are cut off. + let r = read( + "<< /ShadingType 2 /ColorSpace /DeviceRGB /Coords [60 60 90 90] \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill", + ); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + assert!(near(bounds(&n), Rect::new(20.0, 0.0, 100.0, 80.0)), "{:?}", bounds(&n)); + let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") }; + for a in path.subpaths.iter().flat_map(|s| s.anchors.iter()) { + // Back in PostScript's y-up space. + let s = a.p.x + (100.0 - a.p.y); + assert!((120.0 - 1e-6..=180.0 + 1e-6).contains(&s), "{a:?}"); + } + // The current transformation turns the axis: rotated a quarter turn about the centre, an axis + // from -40 to 40 along x runs up the page from y 10 to 90. + let r = read( + "50 50 translate 90 rotate << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [-40 0 40 0] \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill", + ); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + assert!(near(bounds(&n), Rect::new(0.0, 10.0, 100.0, 90.0)), "{:?}", bounds(&n)); + // Radial from a point off the circle's centre covers the hull of that point and the circle. + let b = shade(3, "20 50 0 60 50 30", ""); + assert!((b.x0 - 20.0).abs() < 0.5 && (b.x1 - 90.0).abs() < 0.5 && (b.y0 - 20.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "{b:?}"); + // Radial shadings this doesn't bound (extended at one end, or starting from a circle) still + // paint the whole area. + for (coords, extend) in [("50 50 0 50 50 30", "/Extend [true false]"), ("50 50 0 50 50 30", "/Extend [false true]"), ("50 50 10 50 50 30", "")] { + let b = shade(3, coords, extend); + assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{coords} {extend}: {b:?}"); + } +} + /// A sampled function of one input in an axial shading: interpolated linearly, its gradient has a /// stop at every sample (exact, not sampled evenly); with `Order 3` it is a cubic through the /// samples (PLRM 3rd ed. §3.10.1, Table 3.36), kept in its range. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index dbac845dad..dc0f225872 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5887,12 +5887,18 @@ fn type_envelope_on(keys: &str, shape: &str, drawn: &str, after: &str) -> String /// [`type_envelope_on`] around the type of story `story`. fn type_envelope_on_story(story: u32, keys: &str, shape: &str, drawn: &str, after: &str) -> String { + type_envelope_holding(keys, shape, &format!("{}{after}", text_object(story)), drawn) +} + +/// [`type_envelope_on`] whose contents are `contents` (on plain lines, written on `%_` ones), which +/// hold its text objects. +fn type_envelope_holding(keys: &str, shape: &str, contents: &str, drawn: &str) -> String { let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; format!( "{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", hidden(&format!("u\n{shape}U\n")), hidden(&format!("/ArtDictionary :\n{keys}")), - hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(story))), + hidden(&format!("u\n{contents}U\n9 () XW\n")), ) } @@ -5998,6 +6004,32 @@ fn an_envelope_of_type_that_draws_as_its_drawn_art_opens_live() { assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); } +/// An envelope of type with no fill and no stroke, its drawn art the bent outlines unpainted, opens +/// live: neither draws a pixel, so they draw alike, and the type stays editable. +#[test] +fn an_envelope_of_unpainted_type_whose_drawn_art_paints_nothing_opens_live() { + let Some(family) = installed_family() else { return }; + // The outlines come from the type filled; the file's type has its fill turned off (`/56 false`). + let filled = type_envelope_text(&family, None); + let mut doc = text_document(&[("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0)]) + .replace("(Helvetica)", &format!("({family})")) + .replace("/53 <<", "/56 false /53 <<"); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + assert_eq!(text_fill(&made_envelope_type(&doc)), None); + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&filled), 30.0)); + assert!(drawn.contains("f\n"), "{drawn}"); + let unpainted = drawn.replace("f\n", "n\n"); + let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope(&arc_keys(0.3), &unpainted))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); +} + /// An envelope of type whose live envelope draws apart from its drawn art (the file's art bends the /// other way) keeps its drawn art and its type, hidden, with a note. #[test] @@ -6556,6 +6588,86 @@ fn a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its } } +/// In the layers, type from the text document made a clipping mask (a clipping group with no +/// clipping path, the type last) clips the group's art as the page draws it: the type comes in as +/// the group's clipping path, editable, and the art doesn't paint past it. +#[test] +fn type_made_a_clipping_mask_clips_its_group_in_the_layers() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_bounds}; + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + // The page: the type's glyphs in the yellow of the square they clip, which covers the page, and + // drawn through a flat mesh over their box, which leaves them where they are. + let mut yellow = made_envelope_type(&type_envelope_text(&family, Some("/0 << /0 2 /1 [ 1.0 0.0 0.0 1.0 0.0 ] >>"))); + yellow.visible = true; + let content = vec![std::sync::Arc::new(yellow)]; + let g = envelope_content_bounds(&content).unwrap(); + let points = vec![kurbo::Point::new(g.x0, g.y0), kurbo::Point::new(g.x1, g.y0), kurbo::Point::new(g.x0, g.y1), kurbo::Point::new(g.x1, g.y1)]; + let kind = Box::new(EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![[kurbo::Vec2::ZERO; 4]; 4] }); + let options = EnvelopeOptions::NEW; + let flat = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind, fidelity: 50.0, editing: false, options, frame: Box::default() }, + ); + let (_, page) = drawn_envelope(&flat); + let clipped = format!("q\n0 0 1 0 k\n0 0 m\n100 0 L\n100 100 L\n0 100 L\nf\n{}Q\n", text_object(0)); + let art = native_with_text(&layer("Art", true, &clipped), &doc); + let r = import(&eps(&page, &art)).unwrap(); + // The layers are used, none of their art replaced with the page's (the note on how the type + // differs from the page is about the edges of its glyphs). + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("came in as its art") || w.contains("weren't read")), "{:?}", r.warnings); + let children = r.document.layers[0].children().unwrap(); + let [group] = children.as_slice() else { panic!("{children:#?}") }; + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("not clipped: {group:#?}") }; + let (NodeKind::Text(t), NodeKind::Path { .. }) = (&children[0].kind, &children[1].kind) else { panic!("{children:#?}") }; + assert_eq!(t.plain_text(), "FLUX"); +} + +/// Type made a clipping mask in an envelope's contents (a clipping group with no clipping path, the +/// type last) clips the art under it there, as the drawn art shows: the envelope opens live, its +/// type editable as the group's clipping path. The art it clips covers the type's glyphs and stays +/// inside their box, so the envelope maps from that box however the art past the type would count. +#[test] +fn an_envelope_whose_type_clips_its_contents_opens_live_with_the_type_clipping_them() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + // What it draws: the type in the yellow of the square it clips, which covers it. + let yellow = made_envelope_type(&type_envelope_text(&family, Some("/0 << /0 2 /1 [ 1.0 0.0 0.0 1.0 0.0 ] >>"))); + let shaped = |text: Node| { + let mut text = text; + text.visible = true; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let content = vec![std::sync::Arc::new(text)]; + Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, + ) + }; + let glyphs = vectorcraft_doc::live::envelope_content_bounds(&[std::sync::Arc::new(yellow.clone())]).unwrap(); + let (drawn, page) = drawn_envelope(&shaped(yellow)); + // A yellow square over the glyphs' box, just inside it. + let (x0, y0) = to_art(kurbo::Point::new(glyphs.x0 + 0.01, glyphs.y1 - 0.01)); + let (x1, y1) = to_art(kurbo::Point::new(glyphs.x1 - 0.01, glyphs.y0 + 0.01)); + let contents = format!("q\n0 0 1 0 k\n{x0} {y0} m\n{x1} {y0} L\n{x1} {y1} L\n{x0} {y1} L\nf\n{}Q\n", text_object(0)); + let envelope = type_envelope_holding(&arc_keys(0.3), &rising_grid(), &contents, &drawn); + let art = native_with_text(&layer("Art", true, &format!("{}\n{envelope}", square(10, 10))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); + let mut live = vec![]; + r.document.walk(|n| { + if let NodeKind::Envelope { content, .. } = &n.kind { + live.push(content.clone()); + } + }); + let [content] = live.as_slice() else { panic!("{:?}", r.warnings) }; + let [group] = content.as_slice() else { panic!("{content:#?}") }; + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("not clipped: {group:#?}") }; + let (NodeKind::Text(t), NodeKind::Path { .. }) = (&children[0].kind, &children[1].kind) else { panic!("{children:#?}") }; + assert_eq!(t.plain_text(), "FLUX"); +} + /// A warp of stroked type with Distort Appearance whose drawn art maps the type's bounds with its /// strokes onto the grid the file saves (not its glyphs' bounds alone) opens live as a mesh envelope /// mapping from that box (#3179). The drawn art strokes the bent outlines at the stroke's own weight, @@ -7198,6 +7310,147 @@ fn warped_type_that_draws_apart_from_its_look_comes_in_as_the_look() { } } +/// An art style section with style `Dashed`: a black stroke 2 units wide with butt caps, miter joins +/// and dashes of 6 and gaps of 4, aligned to corners and path ends (`BSDashAdj`). +fn aligned_dash_style() -> String { + "%AI9_BeginArtStyles\n/KnownStyle :\n(Dashed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 2 w 10 M [6 4 ]0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + .to_string() +} + +/// The open path of [`aligned_dash_file`], a corner at (80, 20), in the document's coordinates. +fn aligned_dash_path() -> kurbo::BezPath { + let mut bp = kurbo::BezPath::new(); + bp.move_to((20.0, 20.0)); + bp.line_to((80.0, 20.0)); + bp.line_to((80.0, 70.0)); + bp +} + +/// What [`aligned_dash_style`] draws along [`aligned_dash_path`], with its dashes aligned to corners +/// and path ends by VectorCraft or (`aligned` false) not, as look operators in black. +fn aligned_dash_look(aligned: bool) -> String { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Dash, LineCap, LineJoin, StrokeLayer}; + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); + (stroke.cap, stroke.join, stroke.miter_limit) = (LineCap::Butt, LineJoin::Miter, 10.0); + stroke.dash = Some(Dash { pattern: vec![6.0, 4.0], offset: 0.0, align_corners: aligned }); + let outline = vectorcraft_effects::stroke::line_outline(&aligned_dash_path(), &stroke, 2.0, 0.01); + assert!(!outline.elements().is_empty()); + drawn_as_operators(&outline).replace("0 1 1 0 1 0 0 Xa", "0 0 0 1 0 0 0 Xa") +} + +/// The editing copy of [`aligned_dash_path`] under [`aligned_dash_style`], with the look `drawing`. +fn aligned_dash_file(drawing: &str) -> String { + aligned_dash_files(drawing, 1) +} + +/// [`aligned_dash_file`] with `n` such paths. +fn aligned_dash_files(drawing: &str, n: usize) -> String { + let own = "%_0 0 0 1 0 0 0 XA\n%_2 w\n%_20 80 m\n%_80 80 L\n%_80 30 L\n%_S\n"; + let one = format!("u\n{drawing}\nU\n9 () XW\n{own}1 (Dashed) XW\n"); + native(&(aligned_dash_style() + &layer("Art", true, &one.repeat(n)))) +} + +/// The paths of `d` that stroke with dashes, each with whether its dashes are aligned to corners. +fn dashed_paths(d: &Document) -> Vec { + let mut out = vec![]; + d.walk(|n| { + if matches!(n.kind, NodeKind::Path { .. }) { + for i in &n.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = i + && let Some(dash) = &s.dash + { + out.push(dash.align_corners); + } + } + } + }); + out +} + +/// A stroke whose dashes are aligned to corners and path ends comes in as the path with that stroke, +/// editable, where VectorCraft's fitting draws as its drawn look. +#[test] +fn dashes_aligned_to_corners_that_draw_as_the_look_come_in_live() { + let (d, notes) = crate::ai_alone(&private(&aligned_dash_file(&aligned_dash_look(true)))).unwrap(); + assert_eq!(dashed_paths(&d), [true], "{notes:?}"); + assert!(!notes.iter().any(|w| w.contains("drawn look")), "{notes:?}"); +} + +/// Where the look draws the dashes elsewhere (here, not fitted), the path keeps its drawn look. +#[test] +fn dashes_aligned_to_corners_that_draw_apart_from_the_look_keep_it() { + let (d, notes) = crate::ai_alone(&private(&aligned_dash_file(&aligned_dash_look(false)))).unwrap(); + assert!(dashed_paths(&d).is_empty(), "{notes:?}"); + let looks = d.layers[0].children().unwrap(); + assert!(matches!(looks.as_slice(), [l] if matches!(l.kind, NodeKind::Group { .. }) && l.visual_bounds().is_some()), "{looks:#?}"); +} + +/// The strokes with aligned dashes one import checks against their looks are limited +/// ([`crate::import::ai::MAX_DASH_CHECKS`]), apart from the envelopes' checks: past the +/// limit, a path that would draw as its look keeps the look. +#[test] +fn dashes_aligned_to_corners_past_their_checks_keep_the_look() { + let n = crate::import::ai::MAX_DASH_CHECKS; + let (d, notes) = crate::ai_alone(&private(&aligned_dash_files(&aligned_dash_look(true), n + 1))).unwrap(); + assert_eq!(dashed_paths(&d).len(), n, "{notes:?}"); + let looks = d.layers[0].children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Group { .. })).count(); + assert_eq!(looks, 1); +} + +/// The reads of a file apart from its layers check no stroke with dashes aligned to corners in its +/// layers against its look: the import's checks ([`crate::import::ai::MAX_DASH_CHECKS`]) are its +/// layers' reader's, though those reads go over all of the data. Its artboards and variable library +/// are read with no checks at all, and its swatches (and so its brushes, styles and symbols, read +/// the same way) with none once their reader reaches the layers. The layers' reader still checks +/// the one such stroke. +#[test] +fn the_reads_apart_from_the_layers_check_no_aligned_dashes() { + use vectorcraft_testkit::ai::{sample_variable_sets, variable_library_data}; + let library = variable_library_data(&sample_variable_sets("variableAndTypes", &[])); + let own = "%_0 0 0 1 0 0 0 XA\n%_2 w\n%_20 80 m\n%_80 80 L\n%_80 30 L\n%_S\n"; + let one = format!("u\n{}\nU\n9 () XW\n{own}1 (Dashed) XW\n", aligned_dash_look(true)); + let data = native(&(library + &aligned_dash_style() + &layer("Art", true, &one))); + let checks = |f: &dyn Fn()| { + crate::import::ai::DASH_CHECKS_MADE.set(0); + f(); + crate::import::ai::DASH_CHECKS_MADE.get() + }; + let names = crate::import::ai::Names::default; + assert_eq!(checks(&|| drop(crate::ai_alone(&private(&data)))), 1); + assert_eq!(checks(&|| drop(crate::import::ai::artboards(data.as_bytes(), &mut names()))), 0); + assert_eq!(checks(&|| assert!(crate::import::ai::variables(data.as_bytes(), &mut names()).present)), 0); + assert_eq!(checks(&|| drop(crate::import::ai::palette(data.as_bytes(), &[], &mut names()))), 0); +} + +/// Type under a style with dashes aligned to corners keeps its drawn look, as before, and takes no +/// such stroke: the look check isn't made for type. +#[test] +fn type_with_dashes_aligned_to_corners_keeps_its_drawn_look() { + let doc = text_document(&[("TILT\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); + let look = format!("u\n{}\nU\n9 () XW\n", aligned_dash_look(true)); + let file = native_with_text(&(aligned_dash_style() + &layer("Art", true, &format!("{look}{own}1 (Dashed) XW\n"))), &doc); + let (d, notes) = crate::ai_alone(&private(&file)).unwrap(); + // The look stays, and the type takes no stroke with aligned dashes. + let kids = d.layers[0].children().unwrap(); + assert!(kids.iter().any(|c| matches!(c.kind, NodeKind::Group { .. }) && c.visual_bounds().is_some()), "{notes:?}"); + let mut aligned = false; + d.walk(|n| { + if matches!(n.kind, NodeKind::Text(_)) { + aligned |= n + .appearance + .items + .iter() + .any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Stroke(s) if s.dash.as_ref().is_some_and(|d| d.align_corners))); + } + }); + assert!(!aligned, "{notes:?}"); +} + /// Warped type that a text variable binds stays type with the effect live and keeps its binding, /// though its live warp draws apart from its look. #[test] diff --git a/crates/eps/src/print.rs b/crates/eps/src/print.rs index 0ccd7a6331..1c85e2cf9c 100644 --- a/crates/eps/src/print.rs +++ b/crates/eps/src/print.rs @@ -70,7 +70,7 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec), String> { } let opts = |region: Rect| EpsOptions { level: job.level, region, ..EpsOptions::default() }; let art_opts = opts(r); - let art = Scene::new(p.doc, &art_opts).run(); + let art = Scene::new(p.doc, &art_opts).on_plate(p.ink.is_some()).run(); // The marks' area: the drawing space the page shows (within the tile). let paper = Rect::new(0.0, 0.0, w, h); let shown = if p.view.determinant().abs() > 1e-12 { p.view.inverse().transform_rect_bbox(paper) } else { paper }; diff --git a/crates/eps/src/print/tests.rs b/crates/eps/src/print/tests.rs index 29e7ca0536..8d2f81851c 100644 --- a/crates/eps/src/print/tests.rs +++ b/crates/eps/src/print/tests.rs @@ -1,9 +1,12 @@ //! PostScript print jobs: DSC page comments, the setup of each sheet, and a file the PostScript //! reader reads back. -use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; -use vectorcraft_geom::{Affine, Rect, shapes}; +use vectorcraft_color::{ + Color, Freeform, FreeformPoint, Gradient, GradientGeom, GradientKind, GradientPaint, GradientSpread, GradientStop, Paint, Swatch, +}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, StrokeGradientMode, TextObject}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2, shapes}; +use vectorcraft_testkit::raster::{Image, render_region}; use super::*; @@ -110,3 +113,219 @@ fn separations_screens_flatness_negatives_and_tiles() { assert!(print(&[], &[], &job).is_err()); assert!(print(&[PrintPage { size: (f64::NAN, 1.0), ..page(&d, None) }], &[0], &job).is_err()); } + +/// A 200 × 100 pt CMYK document with spot swatch `Ink` (100% K): a rectangle over the whole page +/// painted `under`, when there is one, then `art`. +fn over(under: Option, art: &[Node]) -> Document { + let mut d = Document::new(200.0, 100.0); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), global: true, spot: true }); + let layer = d.layers[0].id; + let under = under.map(|p| Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::basic(p, Paint::None, 0.0))); + for mut n in under.into_iter().chain(art.iter().cloned()) { + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + d +} + +/// Ink `ink`'s plate of `d` as the print plan separates it for PostScript, and as a PostScript +/// separation at `level` read back, both drawn at 1 px a point. +fn plate_of(d: &Document, ink: &str, level: Level) -> (Image, Image) { + let area = Rect::new(0.0, 0.0, 200.0, 100.0); + let settings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let plan = vectorcraft_pdf::plan(d, &vectorcraft_pdf::PrintOptions { settings, postscript: true, ..Default::default() }).unwrap(); + let i = plan.sheets.iter().find(|s| s.ink.as_ref().is_some_and(|p| p.name == ink)).and_then(|s| s.plate).unwrap(); + let plate = &plan.plates[i]; + let page = PrintPage { + doc: plate, + size: (200.0, 100.0), + view: Affine::IDENTITY, + window: None, + place: Affine::IDENTITY, + copies: &[], + area, + marks: None, + negative: false, + ink: Some((ink, 85.0, 15.0)), + }; + let out = print(&[page], &[0], &PrintJob { level, ..PrintJob::default() }).unwrap(); + assert!(level == Level::Three || !text(&out).contains("shfill"), "Level 2 has no smooth shadings"); + let back = crate::import(&out.bytes).unwrap().document; + (render_region(plate, area, 1.0), render_region(&back, area, 1.0)) +} + +/// Ink `ink`'s PostScript plate of `art` over a page of 100% `ink` (`under`), checked against the +/// plate of `art` alone (drawn from the print plan, or with `postscript` from its PostScript +/// plate): where `art` puts none of the ink down, the ink under it prints, and where it puts ink +/// down, its own amount prints. The pixels of the page where `art` alone puts no ink, those of +/// them where the ink under it does not print, and the pixels where `art` puts ink down that do +/// not print its amount. +fn keeps_the_ink_below(art: &[Node], under: &Paint, ink: &str, level: Level, postscript: bool) -> (usize, usize, usize) { + let (plan, own) = plate_of(&over(None, art), ink, level); + let alone = if postscript { own } else { plan }; + let (_, printed) = plate_of(&over(Some(under.clone()), art), ink, level); + // Pixels whose neighbors all have paper (or all have ink) on the plate of `art` alone: an + // edge falls on either side of a pixel's center, and the edge of the inked part is lightest. + let around = |x: u32, y: u32, paper: bool| { + (x.saturating_sub(1)..=(x + 1).min(alone.width - 1)) + .all(|i| (y.saturating_sub(1)..=(y + 1).min(alone.height - 1)).all(|j| (alone.over_white(i, j)[0] >= 254) == paper)) + }; + let (mut paper, mut knocked_out, mut wrong) = (0, 0, 0); + for y in 0..alone.height { + for x in 0..alone.width { + let (a, p) = (alone.over_white(x, y)[0], printed.over_white(x, y)[0]); + if around(x, y, true) { + paper += 1; + knocked_out += usize::from(p > 60); + } else if around(x, y, false) { + wrong += usize::from(a.abs_diff(p) > 48); + } + } + } + (paper, knocked_out, wrong) +} + +/// A rectangle from (20, 10) to (180, 90) with `fill` and `stroke` (16 pt), each set to +/// overprint. +fn overprinting(fill: Paint, stroke: Paint) -> Node { + let mut n = Node::path(NodeId(0), shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, stroke, 16.0)); + for it in &mut n.appearance.items { + *it.overprint_mut() = true; + } + n +} + +/// `stops` (offset, color) as a `kind` gradient placed at `geom`, spreading as `spread`. +fn gradient(kind: GradientKind, stops: &[(f32, Color)], geom: GradientGeom, spread: GradientSpread) -> Paint { + let stops = stops.iter().map(|(o, c)| GradientStop::new(*o, *c)).collect(); + let mut g = GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::new(kind, stops) }); + g.geom = Some(geom); + Paint::Gradient(Box::new(g)) +} + +#[test] +fn an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate() { + // Cyan in the outer stops, none from 0.3 to 0.6 (magenta only there). + let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0)); + let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)]; + let c = Point::new(100.0, 50.0); + let around = GradientGeom { start: c, end: c + Vec2::new(70.0, -20.0), aspect: 0.7, focal: None }; + let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None }; + let pad = GradientSpread::Pad; + let fills = [ + ("linear", gradient(GradientKind::Linear, &stops, across, pad)), + ("radial", gradient(GradientKind::Radial, &stops, around, pad)), + ("off-center radial", gradient(GradientKind::Radial, &stops, GradientGeom { focal: Some(c + Vec2::new(-20.0, 10.0)), ..around }, pad)), + ("conic", gradient(GradientKind::Conic, &stops, around, pad)), + ("diamond", gradient(GradientKind::Diamond, &stops, around, pad)), + ("repeating linear", gradient(GradientKind::Linear, &stops, across, GradientSpread::Repeat)), + ("reflecting radial", gradient(GradientKind::Radial, &stops, around, GradientSpread::Reflect)), + // A hard edge: two stops at 0.5, the inked half first. + ("hard edge", gradient(GradientKind::Linear, &[(0.0, inked), (0.5, inked), (0.5, none), (1.0, none)], across, pad)), + // Starting and ending with no cyan, padding past both ends. + ("none at the ends", gradient(GradientKind::Linear, &[(0.2, none), (0.4, none), (0.5, inked), (0.8, none)], across, pad)), + ]; + // Many stretches with no cyan. + let many: Vec<(f32, Color)> = (0..16).map(|i| (i as f32 / 15.0, if i % 4 < 2 { inked } else { none })).collect(); + let fills = fills.into_iter().chain([("many stops", gradient(GradientKind::Linear, &many, across, pad))]); + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let cases: Vec<_> = fills.map(|(name, fill)| (name, overprinting(fill, Paint::None), cyan.clone(), "Cyan")).collect(); + assert_keeps_the_ink_below(&cases); +} + +#[test] +fn an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate() { + // Two stops at an end, one with cyan and one without: Level 2's bands pad with the end stop, + // Level 3's shading with the stretch next to it, so each level is checked against its own + // plate of the gradient alone. + let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0)); + let ends = [ + ("none then cyan at 0", [(0.0, none), (0.0, inked), (1.0, inked)]), + ("cyan then none at 1", [(0.0, inked), (1.0, inked), (1.0, none)]), + ("cyan then none at 0", [(0.0, inked), (0.0, none), (1.0, none)]), + ("none then cyan at 1", [(0.0, none), (1.0, none), (1.0, inked)]), + ]; + let c = Point::new(100.0, 50.0); + let around = GradientGeom { start: c, end: c + Vec2::new(50.0, -10.0), aspect: 0.7, focal: None }; + let across = GradientGeom { start: Point::new(40.0, 40.0), end: Point::new(160.0, 60.0), aspect: 1.0, focal: None }; + let pad = GradientSpread::Pad; + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let shapes = [(GradientKind::Linear, across, "linear"), (GradientKind::Radial, around, "radial"), (GradientKind::Diamond, around, "diamond")]; + let mut cases = vec![]; + for (name, stops) in &ends { + for (kind, geom, shape) in shapes { + let fill = gradient(kind, stops, geom, pad); + cases.push((format!("{shape}, {name}"), overprinting(fill, Paint::None), cyan.clone(), "Cyan")); + } + } + let cases: Vec<_> = cases.iter().map(|(name, art, under, ink)| (name.as_str(), art.clone(), under.clone(), *ink)).collect(); + assert_keeps_the_ink_below_of(&cases, true); +} + +/// [`keeps_the_ink_below`] for each of `cases` (a name, the art, the paint under it and the ink +/// of the plate) at Level 3 and Level 2, with every case that fails named. +fn assert_keeps_the_ink_below(cases: &[(&str, Node, Paint, &str)]) { + assert_keeps_the_ink_below_of(cases, false); +} + +/// [`assert_keeps_the_ink_below`], checked against the PostScript plate of each case's art alone +/// with `postscript`. +fn assert_keeps_the_ink_below_of(cases: &[(&str, Node, Paint, &str)], postscript: bool) { + let mut failed = vec![]; + for (name, art, under, ink) in cases { + for level in [Level::Three, Level::Two] { + let (paper, knocked_out, wrong) = keeps_the_ink_below(std::slice::from_ref(art), under, ink, level, postscript); + if knocked_out + wrong >= 100 { + failed.push(format!("{name} at level {level:?}: {knocked_out} of {paper} knocked out, {wrong} of the others differ")); + } + } + } + assert!(failed.is_empty(), "{failed:#?}"); +} + +#[test] +fn overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates() { + let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0)); + let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)]; + let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None }; + let linear = gradient(GradientKind::Linear, &stops, across, GradientSpread::Pad); + let stroked = |mode: StrokeGradientMode| { + let mut n = overprinting(Paint::None, linear.clone()); + if let Some(st) = n.appearance.stroke_mut() { + st.gradient_mode = mode; + } + n + }; + // Type: a gradient placed on the characters' bounds. + let on_type = GradientPaint::new(Gradient::new(GradientKind::Linear, stops.iter().map(|(o, c)| GradientStop::new(*o, *c)).collect())); + let style = CharStyle { fill: Paint::Gradient(Box::new(on_type)), overprint_fill: true, size: 80.0, ..Default::default() }; + let text = Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 85.0), "HIM", style)))); + // A freeform gradient with wide spreads of pure color around its points: none of the cyan + // around the left one. + let mut freeform = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, none), GradientStop::new(1.0, inked)])); + let pure = |at: Point, c: Color| FreeformPoint { spread: 0.9, ..FreeformPoint::new(at, c) }; + let points = vec![pure(Point::new(50.0, 50.0), none), pure(Point::new(150.0, 50.0), inked)]; + freeform.freeform = Some(Freeform { points, ..Default::default() }); + // A spot ink's own plate: its tints in the outer stops, none of it from 0.3 to 0.6. + let tint = |t: f32| GradientStop { swatch: Some("Ink".into()), tint: t, ..GradientStop::new(0.0, Color::cmyk(0.0, 0.0, 0.0, t)) }; + let spot = [ + GradientStop { offset: 0.0, ..tint(0.8) }, + GradientStop::new(0.3, none), + GradientStop::new(0.6, none), + GradientStop { offset: 1.0, ..tint(0.5) }, + ]; + let mut on_spot = GradientPaint::new(Gradient::new(GradientKind::Linear, spot.to_vec())); + on_spot.geom = Some(across); + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let full = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 1.0 }; + let cases = [ + ("stroke within", stroked(StrokeGradientMode::Within), cyan.clone(), "Cyan"), + ("stroke along", stroked(StrokeGradientMode::Along), cyan.clone(), "Cyan"), + ("stroke across", stroked(StrokeGradientMode::Across), cyan.clone(), "Cyan"), + ("type", text, cyan.clone(), "Cyan"), + ("freeform", overprinting(Paint::Gradient(Box::new(freeform)), Paint::None), cyan, "Cyan"), + ("spot", overprinting(Paint::Gradient(Box::new(on_spot)), Paint::None), full, "Ink"), + ]; + assert_keeps_the_ink_below(&cases); +} diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 5bbb1c9fed..feee718176 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use kurbo::Shape; use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint}; +use vectorcraft_doc::overprint::is_white; use vectorcraft_doc::{ AppearanceItem, ColorMode, Document, Effect, ImageBlob, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, SymbolBoxes, TextObject, }; @@ -213,6 +214,14 @@ impl GradientSpace { GradientSpace::Inks(_, n) => *n, } } + + /// Whether components `c` in this space are paper white: no ink, or full light. + fn paper(&self, c: &[f32]) -> bool { + match self { + GradientSpace::Process(Space::Gray | Space::Rgb) => c.iter().all(|v| *v >= 1.0), + GradientSpace::Process(Space::Cmyk) | GradientSpace::Inks(..) => c.iter().all(|v| *v <= 0.0), + } + } } /// A gradient's stops as written: offsets from 0 to 1 and the components in its space. @@ -287,6 +296,12 @@ pub(crate) struct Scene<'a> { max_body: usize, /// Symbols and brush art being written inside one another. nest: u32, + /// The document is a separation's plate: every color is the gray of one ink's coverage + /// ([`Self::on_plate`]). + plate: bool, + /// The gradient being painted overprints on a plate: where it is paper white it puts none of + /// the plate's ink down, and the plate below it is left as it is ([`Self::inked_spans`]). + keep_below: bool, } impl<'a> Scene<'a> { @@ -315,9 +330,19 @@ impl<'a> Scene<'a> { pending: 0, max_body: MAX_BODY, nest: 0, + plate: false, + keep_below: false, } } + /// This scene drawing a separation's plate when `plate` is true: an overprinting gradient + /// paints only where it puts the plate's ink down, as an overprinting solid color that puts + /// none down is drawn as nothing on it. + pub fn on_plate(mut self, plate: bool) -> Self { + self.plate = plate; + self + } + /// This scene with a page body of at most `max` bytes. #[cfg(test)] pub fn with_max_body(mut self, max: usize) -> Self { @@ -689,13 +714,20 @@ impl<'a> Scene<'a> { self.line("q"); push_path(&mut self.body, bp); self.body.push_str(clip_op(rule)); - self.paint_area(p, bounds, bp.bounding_box()); + self.paint_overprinting(overprint, p, bounds, bp.bounding_box()); self.line("Q"); } } self.overprint_off(on); } + /// [`Self::paint_area`] for a fill or stroke that overprints when `overprint` is true. + fn paint_overprinting(&mut self, overprint: bool, p: &Paint, bounds: Rect, area: Rect) { + let keep = std::mem::replace(&mut self.keep_below, self.plate && overprint); + self.paint_area(p, bounds, area); + self.keep_below = keep; + } + /// Paint all of `area` (inside the current clip) with gradient or pattern `p`, placed on /// `bounds`. fn paint_area(&mut self, p: &Paint, bounds: Rect, area: Rect) { @@ -786,7 +818,7 @@ impl<'a> Scene<'a> { self.line("q"); push_path(&mut self.body, bp); self.line("strokepath W"); - self.paint_area(p, paint_bounds, w.reach(st, bounds)); + self.paint_overprinting(st.overprint, p, paint_bounds, w.reach(st, bounds)); self.line("Q"); } } @@ -1152,7 +1184,8 @@ impl<'a> Scene<'a> { /// Paint all of `area` (inside the current clip) with linear, radial, conic or diamond gradient /// `g`, placed on `bounds`: a smooth shading at Level 3, else stepped fills (a conic: wedges at - /// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). + /// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). Overprinting + /// on a plate, it is clipped to the levels where it puts ink down ([`Self::inked_spans`]). fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) { let geom = g.resolve(bounds); // One mixed around the hue wheel that reflects is repeated from its curve's stops, which @@ -1185,7 +1218,7 @@ impl<'a> Scene<'a> { } let (space, stops) = self.gradient_stops(&g.gradient); if !stops.windows(2).any(|w| w[1].0 > w[0].0) { - if let Some((_, c)) = stops.first() { + if let Some((_, c)) = stops.first().filter(|(_, c)| !(self.keep_below && space.paper(c))) { self.set_comps(&space, c); self.rect_fill(area); } @@ -1193,20 +1226,47 @@ impl<'a> Scene<'a> { } let space = &space; let smooth = self.o.level == Level::Three && !self.o.compatible_gradients; + let spans = if g.gradient.kind == GradientKind::Conic { None } else { self.inked_spans(space, &stops, smooth) }; match g.gradient.kind { GradientKind::Conic => self.conic_steps(&geom, area, space, &stops, &g.gradient), - GradientKind::Diamond => self.diamond_quadrants(&geom, area, space, &stops, smooth), + GradientKind::Diamond => { + // Its levels are diamonds about the center, the square's edge at 1. + let frame = geom.diamond_frame(); + if let Some(spans) = &spans { + let Some(frame) = frame else { + // Without a frame it is its last stop everywhere. + if stops.last().is_some_and(|(_, c)| !space.paper(c)) { + self.diamond_quadrants(&geom, area, space, &stops, smooth); + } + return; + }; + let level = |t: f64| (t > 0.0).then(|| frame * BezPath::from_vec(diamond(t))); + self.line("q"); + let clipped = self.clip_rings(spans, area.inflate(1.0, 1.0), level); + if clipped { + self.diamond_quadrants(&geom, area, space, &stops, smooth); + } + self.line("Q"); + return; + } + self.diamond_quadrants(&geom, area, space, &stops, smooth); + } GradientKind::Radial => { let r = geom.length().max(1e-6); let squash = geom.radial_squash(); let inv = squash.inverse(); let (f, c) = (inv * geom.focal_point(), geom.start); + let local = inv.transform_rect_bbox(area); self.line("q"); let _ = writeln!(self.body, "{} cm", ps::matrix(squash)); - if smooth { - self.shading(3, space, &[f.x, f.y, 0.0, c.x, c.y, r], &stops); - } else { - self.radial_steps(f, c, r, inv.transform_rect_bbox(area), space, &stops); + // Its levels are circles from the focal point, at 1 the circle of radius `r`. + let level = |t: f64| (t > 0.0).then(|| kurbo::Circle::new(f + (c - f) * t, r * t).to_path(0.01)); + if spans.as_ref().is_none_or(|spans| self.clip_rings(spans, local.inflate(1.0, 1.0), level)) { + if smooth { + self.shading(3, space, &[f.x, f.y, 0.0, c.x, c.y, r], &stops); + } else { + self.radial_steps(f, c, r, local, space, &stops); + } } self.line("Q"); } @@ -1215,15 +1275,122 @@ impl<'a> Scene<'a> { if s.distance(e) < 1e-9 { e = s + Vec2::new(1.0, 0.0); } - if smooth { - self.shading(2, space, &[s.x, s.y, e.x, e.y], &stops); + if let Some(spans) = &spans { + self.line("q"); + if self.clip_strips(spans, s, e, area) { + self.linear(s, e, area, space, &stops, smooth); + } + self.line("Q"); } else { - self.linear_steps(s, e, area, space, &stops); + self.linear(s, e, area, space, &stops, smooth); } } } } + /// A linear gradient from `s` to `e` over `area`: a smooth shading, else stepped fills. + fn linear(&mut self, s: Point, e: Point, area: Rect, space: &GradientSpace, stops: &[(f64, Vec)], smooth: bool) { + if smooth { + self.shading(2, space, &[s.x, s.y, e.x, e.y], stops); + } else { + self.linear_steps(s, e, area, space, stops); + } + } + + /// Where an overprinting gradient with `stops` in `space` puts ink on a plate + /// ([`Self::keep_below`]): the spans of its levels outside every stretch between two stops of + /// paper white and outside the padding past an end painted paper white, in order, an end + /// padding with ink unbounded. The padding takes the end stop's color when stepped and the + /// end stretch's color when `smooth` ([`Self::shading`]); the two differ when two stops share + /// the end's offset. `None` when the gradient puts ink everywhere or does not overprint on a + /// plate; empty when it puts none down. + fn inked_spans(&self, space: &GradientSpace, stops: &[(f64, Vec)], smooth: bool) -> Option> { + if !self.keep_below { + return None; + } + let stretches: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect(); + let (first, last) = (stretches.first()?, stretches.last()?); + let (start, end) = if smooth { (&first[0].1, &last[1].1) } else { (&stops.first()?.1, &stops.last()?.1) }; + let (before, after) = (space.paper(start), space.paper(end)); + let mut blank: Vec<(f64, f64)> = vec![]; + let mut add = |a: f64, b: f64| match blank.last_mut() { + Some(l) if l.1 >= a => l.1 = l.1.max(b), + _ => blank.push((a, b)), + }; + if before { + add(f64::NEG_INFINITY, first[0].0); + } + for w in &stretches { + if space.paper(&w[0].1) && space.paper(&w[1].1) { + add(w[0].0, w[1].0); + } + } + if after { + add(last[1].0, f64::INFINITY); + } + if blank.is_empty() { + return None; + } + let mut inked = vec![]; + let mut from = f64::NEG_INFINITY; + for (a, b) in blank { + if a > from { + inked.push((from, a)); + } + from = b; + } + if from < f64::INFINITY { + inked.push((from, f64::INFINITY)); + } + Some(inked) + } + + /// Clip to the parts of `area` where a linear gradient from `s` to `e` has a level in `spans`: + /// a strip across the gradient for each. False, with nothing written, when no span reaches + /// into `area`. + fn clip_strips(&mut self, spans: &[(f64, f64)], s: Point, e: Point, area: Rect) -> bool { + let d = e - s; + let len = d.hypot(); + // Gradient space: x along the gradient (0 to 1), y across it in points. + let frame = Affine::new([d.x, d.y, -d.y / len, d.x / len, s.x, s.y]); + let local = frame.inverse().transform_rect_bbox(area.inflate(1.0, 1.0)); + let mut bp = BezPath::new(); + for &(a, b) in spans { + let (a, b) = (a.max(local.x0), b.min(local.x1)); + if a < b { + bp.extend((frame * Rect::new(a, local.y0, b, local.y1).to_path(0.1)).iter()); + } + } + self.clip_path(&bp, FillRule::NonZero) + } + + /// Clip to the levels in `spans` of a gradient whose level `t` is bounded by `level(t)` (a + /// closed path holding every lower level; `None` for a level without area): for each span + /// the ring between its levels, an unbounded end at `outer`, even-odd. False, with nothing + /// written, when no span has area. + fn clip_rings(&mut self, spans: &[(f64, f64)], outer: Rect, level: impl Fn(f64) -> Option) -> bool { + let mut bp = BezPath::new(); + for &(a, b) in spans { + let edge = if b.is_finite() { level(b) } else { Some(outer.to_path(0.1)) }; + let Some(edge) = edge else { continue }; + bp.extend(edge.iter()); + if let Some(inner) = level(a).filter(|_| a.is_finite()) { + bp.extend(inner.iter()); + } + } + self.clip_path(&bp, FillRule::EvenOdd) + } + + /// Clip to `bp` by `rule`. False, with nothing written, when `bp` is empty. + fn clip_path(&mut self, bp: &BezPath, rule: FillRule) -> bool { + if bp.elements().is_empty() { + return false; + } + push_path(&mut self.body, bp); + self.body.push_str(clip_op(rule)); + true + } + /// A conic gradient as [`CONIC_WEDGE_COUNT`] solid wedges about its center covering `area` /// (PostScript has no conic shading), each running on to the seam under the next, so no /// hairline shows between neighbors ([`vectorcraft_color::GradientGeom::conic_wedges`]). @@ -1243,7 +1410,24 @@ impl<'a> Scene<'a> { Some(w) => w[1].1.clone(), None => stops.last().map_or_else(Vec::new, |s| s.1.clone()), }; - for (pts, t) in geom.conic_wedges(area, g.conic_wedge_count(CONIC_WEDGE_COUNT), true) { + let count = g.conic_wedge_count(CONIC_WEDGE_COUNT); + // Overprinting on a plate: clipped to the wedges that put ink down, each up to the next. + let clipped = self.keep_below && { + let wedges = geom.conic_wedges(area, count, false); + let inked: Vec<_> = wedges.iter().filter(|(_, t)| !space.paper(&at(spread(*t)))).collect(); + if inked.is_empty() { + return; + } + inked.len() < wedges.len() && { + let mut bp = BezPath::new(); + for (pts, _) in inked { + bp.extend(BezPath::from_vec(polygon(pts)).iter()); + } + self.line("q"); + self.clip_path(&bp, FillRule::NonZero) + } + }; + for (pts, t) in geom.conic_wedges(area, count, true) { self.set_comps(space, &at(spread(t))); for (i, p) in pts.iter().enumerate() { push_nums(&mut self.body, &[p.x, p.y]); @@ -1251,6 +1435,9 @@ impl<'a> Scene<'a> { } self.line("closepath fill"); } + if clipped { + self.line("Q"); + } } /// A diamond gradient over `area` as four linear gradients, each clipped to a quadrant of its @@ -1442,20 +1629,68 @@ impl<'a> Scene<'a> { let field = g.freeform_on(b).model_field(spread_scale(b)); let q = |v: f32| (unit(v) * 255.0).round() as u8; let (w, h) = (u32::from(cols), u32::from(rows)); + // Overprinting on a plate: the cells of paper white put none of the ink down, so they are + // left out, as clear pixels at Level 3 and outside a clip of the other cells at Level 2. + let blank: Option> = self.keep_below.then(|| field.grid(area, cols, rows).map(|(c, _)| is_white(&Paint::solid(c))).collect()); + let blank = blank.filter(|b| b.contains(&true)); + if blank.as_ref().is_some_and(|b| !b.contains(&false)) { + return; + } + let keyed = self.o.level == Level::Three; + let clear = |i: usize, a: u8| if keyed && blank.as_ref().is_some_and(|b| b[i]) { 0 } else { a }; let image = if field.model() == Some(Model::Cmyk) || (self.cmyk && field.model() == Some(Model::Gray)) { let inks: Vec = field .grid(area, cols, rows) - .flat_map(|(color, a)| { + .enumerate() + .flat_map(|(i, (color, a))| { let [c, m, y, k] = color.to_cmyk(); - [q(c), q(m), q(y), q(k), q(a)] + [q(c), q(m), q(y), q(k), clear(i, q(a))] }) .collect(); self.encode_inks(&inks, w, h) } else { - let rgba: Vec = field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect(); + let rgba: Vec = + field.display_grid(area, cols, rows).enumerate().flat_map(|(i, (c, a))| [q(c[0]), q(c[1]), q(c[2]), clear(i, q(a))]).collect(); self.encode_image(&rgba, w, h) }; let Some(image) = image else { return }; + let cells = blank.filter(|_| !keyed).map(|b| { + let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows)); + let mut bp = BezPath::new(); + for (row, line) in b.chunks(usize::from(cols)).enumerate() { + let mut col = 0; + while col < line.len() { + let start = col; + while col < line.len() && !line[col] { + col += 1; + } + if col > start { + let (y0, y1) = (area.y0 + row as f64 * ch, area.y0 + (row + 1) as f64 * ch); + bp.extend(Rect::new(area.x0 + start as f64 * cw, y0, area.x0 + col as f64 * cw, y1).to_path(0.1).iter()); + } + col += 1; + } + } + bp + }); + if let Some(bp) = &cells { + // Each row's run of cells is a rectangle of five path elements, about 60 bytes. + if self.size().saturating_add(bp.elements().len().saturating_mul(12)).saturating_add(image.inline_len) > self.max_body { + self.warn(TOO_LARGE); + return; + } + self.line("q"); + self.clip_path(bp, FillRule::NonZero); + } + self.place_field(image, place); + if cells.is_some() { + self.line("Q"); + } + } + + /// Place freeform gradient image `image` on the unit square mapped by `place`, drawn from an + /// image already kept when one is encoded the same. + fn place_field(&mut self, image: ImageCode, place: Affine) { let key = image.content_key(); let found = self.fields.get(&key).and_then(|bucket| bucket.iter().copied().find(|&i| self.codes.get(i).is_some_and(|c| c.same_image(&image)))); @@ -1849,6 +2084,19 @@ fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static code } +/// The closed polygon through `pts`. +fn polygon(pts: &[Point]) -> Vec { + let mut els: Vec = + pts.iter().enumerate().map(|(i, p)| if i == 0 { kurbo::PathEl::MoveTo(*p) } else { kurbo::PathEl::LineTo(*p) }).collect(); + els.push(kurbo::PathEl::ClosePath); + els +} + +/// The square with corners (±`t`, 0) and (0, ±`t`). +fn diamond(t: f64) -> Vec { + polygon(&[Point::new(t, 0.0), Point::new(0.0, t), Point::new(-t, 0.0), Point::new(0.0, -t)]) +} + /// `a` to `b` at `t`. fn mix(a: &[f32], b: &[f32], t: f32) -> Vec { a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect() diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 8e7149cad2..e8f3c42b8e 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -9,6 +9,10 @@ //! are on disk, and the error names them. Where that copy of the old file can't be made, the file //! is left as it was and the save fails. //! +//! Work canceled ([`vectorcraft_doc::cancel`]) by the time the temporary file is written and flushed +//! puts nothing in place: the temporary file is removed, the file stays as it was (or absent), and +//! the error wraps [`vectorcraft_doc::cancel::Cancelled`]. +//! //! On macOS `File::sync_all` is a full flush (`F_FULLFSYNC`), which SMB shares refuse with //! `ENOTSUP` and virtiofs shares (folders shared into a macOS VM) with `ENOTTY`, while a plain //! `fsync` works: [`sync_file`] falls back to the plain one there (#1620). @@ -43,7 +47,8 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { } /// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails the temporary file is removed and `path` is left untouched. When the +/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the +/// temporary file is removed and `path` is left untouched. When the /// folder refuses the temporary file or the rename, the content is copied into `path` instead (see /// the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { @@ -79,7 +84,7 @@ fn write_atomic_stepping( (tmp, f, Some(e)) } }; - let filled = fill(&mut f).and_then(|()| sync_file(&f)); + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); if let Err(e) = filled { // Best effort: the temporary file is all there is to clean up. @@ -176,7 +181,7 @@ fn write_new_linking( ) -> io::Result<()> { let tmp = temp_path(path)?; let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?; - let filled = fill(&mut f).and_then(|()| sync_file(&f)); + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); let placed = filled.and_then(|()| match link(&tmp, path) { Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(&tmp, path), @@ -187,6 +192,12 @@ fn write_new_linking( placed } +/// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has +/// been canceled: the last check before a written temporary file is put in place. +fn not_cancelled() -> io::Result<()> { + vectorcraft_doc::cancel::check().map_err(io::Error::other) +} + /// Create `path` (never replacing anything) with the content of the file `from`; a failed copy /// removes it again. fn copy_new(from: &Path, path: &Path) -> io::Result<()> { @@ -408,6 +419,39 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Work canceled by the time the temporary file is written and flushed puts nothing in place: + /// the old file stays as it was, also where the folder refuses the rename (no copy over it), a + /// new file is not created, and no temporary file is left. + #[test] + fn canceled_work_puts_nothing_in_place() { + use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope}; + fn cancelled(e: &io::Error) -> bool { + e.get_ref().is_some_and(|e| e.is::()) + } + let d = dir("cancel"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"original").unwrap(); + let token = CancelToken::new(); + let r = scope(&token, None, || { + write_atomic_with(&path, |f| { + f.write_all(b"new")?; + token.cancel(); + Ok(()) + }) + }); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + let refused = |_: &Path, _: &Path| -> io::Result<()> { Err(io::Error::from(io::ErrorKind::PermissionDenied)) }; + let r = scope(&token, None, || write_atomic_stepping(&path, |f| f.write_all(b"new"), create_new, refused)); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + let new = d.join("new.vectorcraft"); + let r = scope(&token, None, || write_new_with(&new, |f| f.write_all(b"new"))); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + assert!(!new.exists()); + assert!(leftovers(&d, "doc.vectorcraft").is_empty(), "{:?}", leftovers(&d, "doc.vectorcraft")); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn the_original_file_survives_a_failed_write() { let d = dir("fail"); diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index c5343171ef..abd72b255e 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -158,10 +158,56 @@ impl Anchor { let dir = p - pos; let l = dir.hypot(); if l > 1e-9 { - *other = p + dir * (len / l); + let turned = p + dir * (len / l); + if turned.is_finite() { + *other = turned; + } else { + // Long handles overflow the squares above: measure with `f64::hypot` and scale + // the unit direction, leaving the handle where it is if that is not finite. + let (v, l) = (*other - p, dir.x.hypot(dir.y)); + let turned = p + (dir / l) * v.x.hypot(v.y); + if turned.is_finite() { + *other = turned; + } + } } } } + /// Place the end of the outgoing (`out`) or incoming handle at `pos` and make the anchor smooth: + /// the other handle turns to lie in line with it on the far side of the anchor, at its own + /// length. A retracted other handle is pulled out to the moved handle's length when `pull_out` + /// and stays retracted otherwise. A handle placed on the anchor, or where the turned handle's + /// end would not be a finite point, gives no direction: it is placed, and the other handle and + /// the anchor's kind stay as they are. + pub fn link_handle(&mut self, out: bool, pos: Point, pull_out: bool) { + let p = self.p; + let (moved, other) = if out { (&mut self.h_out, &mut self.h_in) } else { (&mut self.h_in, &mut self.h_out) }; + *moved = pos; + // `f64::hypot` keeps long handles from overflowing the square of their length. + let dir = p - pos; + let l = dir.x.hypot(dir.y); + if !(l > EPS && l.is_finite()) { + return; + } + let v = *other - p; + let len = v.x.hypot(v.y); + let len = if len > EPS { + len + } else if pull_out { + l + } else { + 0.0 + }; + if len > 0.0 { + // The unit direction first, so a short handle does not overflow the scale factor. + let turned = p + (dir / l) * len; + if !turned.is_finite() { + return; + } + *other = turned; + } + self.kind = AnchorKind::Smooth; + } /// Swap handles (used when reversing path direction). pub fn reversed(&self) -> Self { Self { p: self.p, h_in: self.h_out, h_out: self.h_in, kind: self.kind } @@ -280,6 +326,11 @@ impl SubPath { pub fn polyline(points: &[Point], closed: bool) -> Self { Self { anchors: points.iter().map(|&p| Anchor::corner(p)).collect(), closed } } + /// Whether anchor `ai` has a segment on its outgoing (`out`) or incoming side. + pub fn has_segment(&self, ai: usize, out: bool) -> bool { + let n = self.anchors.len(); + ai < n && n > 1 && (self.closed || if out { ai + 1 < n } else { ai > 0 }) + } /// Number of segments (a closed path has one more, back to the start). pub fn segment_count(&self) -> usize { let n = self.anchors.len(); @@ -1103,4 +1154,73 @@ mod tests { let back: PathData = serde_json::from_str(&s).unwrap(); assert_eq!(p, back); } + + /// `link_handle` makes a corner smooth: the other handle turns onto the far side of the anchor + /// at its own length; a retracted one is pulled out to the moved handle's length only when + /// asked, and a handle placed on the anchor changes nothing else. + #[test] + fn link_handle_makes_a_corner_smooth_keeping_the_other_length() { + let p = Point::new(10.0, 10.0); + let mut a = Anchor { p, h_in: Point::new(10.0, 0.0), h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner }; + a.link_handle(true, Point::new(14.0, 13.0), false); + assert_eq!(a.kind, AnchorKind::Smooth); + assert_eq!(a.h_out, Point::new(14.0, 13.0)); + // The in handle keeps its length of 10, opposite the out handle's direction (4, 3) / 5. + assert!(a.h_in.distance(Point::new(2.0, 4.0)) < 1e-9, "{:?}", a.h_in); + + let retracted = Anchor { p, h_in: p, h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner }; + let mut pulled = retracted; + pulled.link_handle(true, Point::new(13.0, 14.0), true); + assert_eq!((pulled.kind, pulled.h_in), (AnchorKind::Smooth, Point::new(7.0, 6.0))); + let mut kept = retracted; + kept.link_handle(true, Point::new(13.0, 14.0), false); + assert_eq!((kept.kind, kept.h_in), (AnchorKind::Smooth, p)); + + let mut on_anchor = Anchor { p, h_in: Point::new(10.0, 0.0), h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner }; + on_anchor.link_handle(false, p, true); + assert_eq!(on_anchor, Anchor { p, h_in: p, h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner }); + + // A handle so far away that its distance overflows leaves the other handle finite. + let far = Point::new(1.7e308, 1.7e308); + let mut overflow = retracted; + overflow.link_handle(true, far, true); + assert_eq!(overflow, Anchor { p, h_in: p, h_out: far, kind: AnchorKind::Corner }); + // A very long other handle turned by a very short one stays finite, at its own length. + let mut long = Anchor { p: Point::ZERO, h_in: Point::new(1e308, 0.0), h_out: Point::ZERO, kind: AnchorKind::Corner }; + long.link_handle(true, Point::new(0.0, 1e-8), false); + assert_eq!((long.kind, long.h_in), (AnchorKind::Smooth, Point::new(0.0, -1e308))); + // One whose turned end would leave the finite range is left where it is. + let edge = Point::new(-1.5e308, 0.0); + let mut beyond = Anchor { p: edge, h_in: Point::new(1.5e308, 0.0), h_out: edge, kind: AnchorKind::Corner }; + beyond.link_handle(true, Point::new(-1.5e308 + 1e300, 0.0), false); + assert_eq!((beyond.kind, beyond.h_in), (AnchorKind::Corner, Point::new(1.5e308, 0.0))); + } + + /// `set_handle` on a smooth anchor turns a very long other handle without overflowing, and + /// leaves it where it is when its turned end would not be a finite point. + #[test] + fn set_handle_on_a_smooth_anchor_keeps_long_handles_finite() { + let mut long = Anchor { p: Point::ZERO, h_in: Point::new(-1e308, 0.0), h_out: Point::new(1.0, 0.0), kind: AnchorKind::Smooth }; + long.set_handle(true, Point::new(0.0, 1e-8), false); + assert_eq!(long.h_in, Point::new(0.0, -1e308)); + let edge = Point::new(-1.5e308, 0.0); + let mut beyond = Anchor { p: edge, h_in: Point::new(-1.6e308, 0.0), h_out: Point::new(1.5e308, 0.0), kind: AnchorKind::Smooth }; + beyond.set_handle(false, Point::new(-1.5e308 + 1e300, 0.0), false); + assert_eq!(beyond.h_out, Point::new(1.5e308, 0.0)); + } + + /// `has_segment` sees a segment on each side of an inner anchor, none past an open path's ends, + /// and both sides on a closed path of two anchors or more. + #[test] + fn has_segment_follows_the_open_ends() { + let pts = [Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)]; + let open = SubPath::polyline(&pts, false); + assert!(!open.has_segment(0, false) && open.has_segment(0, true)); + assert!(open.has_segment(1, false) && open.has_segment(1, true)); + assert!(open.has_segment(2, false) && !open.has_segment(2, true)); + assert!(!open.has_segment(3, false)); + let closed = SubPath::polyline(&pts, true); + assert!(closed.has_segment(0, false) && closed.has_segment(2, true)); + assert!(!SubPath::polyline(&pts[..1], true).has_segment(0, true)); + } } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 98327a2b61..380d161ecf 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -327,7 +327,7 @@ fn install_errors(interp: &mut Interp, object_proto: ObjId) -> JsResult<()> { for (i, (name, f)) in kinds.into_iter().enumerate() { // Error.prototype and each NativeError prototype are Error objects (sections 15.11.4 and // 15.11.7.7). - let proto = alloc(interp, Class::Error, Some(if i == 0 { object_proto } else { error_proto })); + let proto = alloc(interp, Class::Error(None), Some(if i == 0 { object_proto } else { error_proto })); if i == 0 { error_proto = proto; method(interp, proto, "toString", error_to_string, 0)?; diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 3b96953e8d..f612b00138 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -215,7 +215,9 @@ pub(crate) enum Class { length_writable: bool, }, Function(Func), - Error, + /// An error object. One the interpreter threw itself holds a hash of the description it had + /// then ([`crate::interp::Interp::describe`]); one a script made holds `None`. + Error(Option), Arguments(Box), /// A `Boolean` object made by ToObject, with its primitive value. Boolean(bool), @@ -313,7 +315,7 @@ impl Class { Class::Ordinary | Class::ForIn(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", - Class::Error => "Error", + Class::Error(_) => "Error", Class::Arguments(_) => "Arguments", Class::Boolean(_) => "Boolean", Class::Number(_) => "Number", diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index d81e12f3ac..24c33d2fc5 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -48,6 +48,14 @@ fn internal(message: &str) -> JsResult { Err(Abrupt::Internal(message.into())) } +/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]). +fn description_hash(text: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + text.hash(&mut h); + h.finish() +} + /// The kinds of error object the engine throws. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ErrorType { @@ -60,6 +68,21 @@ pub(crate) enum ErrorType { Uri, } +impl ErrorType { + /// The `name` the prototype of this kind of error has before a script changes it. + pub(crate) fn name(self) -> &'static str { + match self { + ErrorType::Error => "Error", + ErrorType::Eval => "EvalError", + ErrorType::Range => "RangeError", + ErrorType::Reference => "ReferenceError", + ErrorType::Syntax => "SyntaxError", + ErrorType::Type => "TypeError", + ErrorType::Uri => "URIError", + } + } +} + /// The objects the interpreter itself refers to. #[derive(Clone, Copy, Debug)] pub(crate) struct Intrinsics { @@ -538,15 +561,34 @@ impl Interp { pub(crate) fn error_object(&mut self, t: ErrorType, message: &str) -> ObjId { let proto = self.intrinsics.error_proto(t); - let mut o = Object::new(Class::Error, Some(proto)); + let mut o = Object::new(Class::Error(None), Some(proto)); if !message.is_empty() { o.props.insert(key("message"), Prop::Data { value: Value::str(message), flags: HIDDEN }); } self.heap.alloc_object(o) } + /// An error of the interpreter's or a host function's own, marked as such with a hash of the + /// description it has with its kind's own name ([`Self::thrown_by_script`]), so a name a script + /// gave the kind's prototype before the error was made counts as the script's text. pub(crate) fn throw(&mut self, t: ErrorType, message: &str) -> Abrupt { - Abrupt::Throw(Value::Object(self.error_object(t, message))) + let o = self.error_object(t, message); + let own = if message.is_empty() { t.name().to_string() } else { format!("{}: {message}", t.name()) }; + if let Some(object) = self.heap.object_mut(o) { + object.class = Class::Error(Some(description_hash(&own))); + } + Abrupt::Throw(Value::Object(o)) + } + + /// Is the text [`Self::describe`] gives for the thrown value `v` the script's own? It is unless + /// `v` is an error the interpreter or a host function threw, with its name and message as they + /// were then: a value the script threw, an error it made, and an error whose name or message it + /// changed all hold its own text. + pub(crate) fn thrown_by_script(&mut self, v: &Value) -> bool { + let Value::Object(o) = v else { return true }; + let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true }; + let hash = *hash; + description_hash(&self.describe(v)) != hash } pub(crate) fn type_error(&mut self, message: &str) -> Abrupt { @@ -819,7 +861,7 @@ impl Interp { let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); if !passed && let Value::Object(o) = v - && self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error)) + && self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error(_))) { self.last_error = v.clone(); } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 9f9c59a96f..bfe358bc20 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -239,6 +239,44 @@ fn errors_carry_line_and_column() { assert_eq!(e.message, "42"); } +/// A run error says whether its message is the script's own text, whatever that text reads: an +/// error the interpreter or a host function threw is not, even when a script caught it and threw +/// it again, and a value or error the script made, or an error whose name or message it changed, +/// is. +#[test] +fn script_error_origin_distinguishes_native_and_authored_values() { + let native = "RangeError: invalid array length"; + for (src, message, authored) in [ + ("new Array(-1)", native, false), + ("try { new Array(-1); } catch (e) { throw e; }", native, false), + ("try { new Array(-1); } catch (e) { e.message = 'invalid array length'; throw e; }", native, false), + ("nope()", "ReferenceError: nope is not defined", false), + ("throw new RangeError('invalid array length')", native, true), + ("throw new Error('invalid array length')", "Error: invalid array length", true), + ("throw 'invalid array length'", "invalid array length", true), + ("throw 17", "17", true), + ("throw {}", "[object Object]", true), + ("throw new Error()", "Error", true), + ("try { new Array(-1); } catch (e) { throw e.message; }", "invalid array length", true), + ("try { new Array(-1); } catch (e) { throw new RangeError(e.message); }", native, true), + ("try { new Array(-1); } catch (e) { e.message = 'mine'; throw e; }", "RangeError: mine", true), + ("try { nope(); } catch (e) { e.name = 'TypeError'; throw e; }", "TypeError: nope is not defined", true), + ("try { new Array(-1); } catch (e) { RangeError.prototype.name = 'Mine'; throw e; }", "Mine: invalid array length", true), + ("RangeError.prototype.name = 'Mine'; new Array(-1)", "Mine: invalid array length", true), + ("RangeError.prototype.name = 'RangeError'; new Array(-1)", native, false), + ] { + let e = fail(src); + assert_eq!((e.kind, e.message.as_str(), e.authored), (RunErrorKind::Thrown, message, authored), "{src}"); + } + assert!(!fail("var x = ;").authored, "a syntax error"); + let mut realm = Realm::new(); + realm.define_function("add", |_| Err("add takes two numbers".into())); + let e = realm.run("add()").unwrap_err(); + assert_eq!((e.message.as_str(), e.authored), ("Error: add takes two numbers", false), "a host function's error"); + let e = realm.run("throw new Error('add takes two numbers')").unwrap_err(); + assert_eq!((e.message.as_str(), e.authored), ("Error: add takes two numbers", true)); +} + /// An error about a property of `null` or `undefined` names a computed property whose name is a /// primitive, and says whether the script read or set it, never naming an empty property; a /// member assignment, an object key and a long name leave the name out. diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 0a1006a23c..d675e82ec7 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -139,6 +139,10 @@ pub struct RunError { pub message: String, pub line: u32, pub column: u32, + /// `message` is text the script supplied: a value it threw, or an error object it made or whose + /// name or message it changed. False for the interpreter's and host functions' own errors, + /// syntax errors and limits, even when a script caught one and threw it again. + pub authored: bool, } impl std::fmt::Display for RunError { @@ -151,7 +155,7 @@ impl std::error::Error for RunError {} impl From for RunError { fn from(e: SyntaxError) -> Self { - RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column } + RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column, authored: false } } } @@ -241,7 +245,7 @@ impl Realm { self.script_tag = UNKNOWN_SOURCE; let interp = &mut self.interp; if let Some(message) = &interp.install_error { - return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 }); + return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false }); } interp.fuel = interp.limits.fuel; interp.flattened_fuel.set(0); @@ -269,7 +273,7 @@ impl Realm { interp.error_tag = self.script_tag; Err(e.into()) } - Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), + Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }), } } @@ -293,15 +297,18 @@ impl Realm { Ok(v) => Ok(interp.to_js_value(&v)), Err(Abrupt::Throw(v)) => { let message = interp.describe(&v); + let authored = interp.thrown_by_script(&v); interp.last_thrown = v; - Err(RunError { kind: RunErrorKind::Thrown, message, line, column }) + Err(RunError { kind: RunErrorKind::Thrown, message, line, column, authored }) } Err(Abrupt::Limit(LimitKind::Host)) => { let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); - Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column }) + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false }) } - Err(Abrupt::Limit(kind)) => Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column }), - Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column }), + Err(Abrupt::Limit(kind)) => { + Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false }) + } + Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column, authored: false }), } } @@ -323,10 +330,16 @@ impl Realm { pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; if interp.frames.is_empty() { - return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0 }); + return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false }); } if interp.waiting { - return Err(RunError { kind: RunErrorKind::Internal, message: "the run waits for a host function's result".into(), line: 0, column: 0 }); + return Err(RunError { + kind: RunErrorKind::Internal, + message: "the run waits for a host function's result".into(), + line: 0, + column: 0, + authored: false, + }); } let total = interp.fuel; let cap = slice.saturating_add(self.unbroken_fuel).min(total); @@ -384,7 +397,13 @@ impl Realm { pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; if !interp.waiting { - return Err(RunError { kind: RunErrorKind::Internal, message: "no host function waits for a result".into(), line: 0, column: 0 }); + return Err(RunError { + kind: RunErrorKind::Internal, + message: "no host function waits for a result".into(), + line: 0, + column: 0, + authored: false, + }); } interp.waiting = false; // The value on top of the stack stood in for the result. diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 2c16587227..870f4a23a3 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -323,6 +323,7 @@ fn headless_command_list_includes_ui_commands() { "app.quit", "window.arrange.tile", "align.horizontalLeft", + "align.toKeyObject", "ui.action.play", ]; for (n, id) in want.iter().enumerate() { @@ -1692,6 +1693,14 @@ fn transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing() { assert_eq!(applied["isError"], false, "{applied}"); let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); assert_eq!(applied["applied"], json!(["move"])); + let applied = call(&mut s, 21, "transform", json!({"ids": [second], "rotate": 90, "origin": null})); + assert_eq!(applied["isError"], false, "{applied}"); + // The schema allows null for every argument but `ids`. + let tools = tool_definitions(); + let props = &tools.iter().find(|t| t["name"] == "transform").unwrap()["inputSchema"]["properties"]; + for key in ["dx", "dy", "rotate", "scale", "scaleX", "scaleY", "shear", "reflect", "copy", "origin"] { + assert!(props[key]["anyOf"].as_array().is_some_and(|a| a.contains(&json!({"type": "null"}))), "{key}: {}", props[key]); + } } #[test] diff --git a/crates/mcp/src/tests/shapewidgets.rs b/crates/mcp/src/tests/shapewidgets.rs index 3ef209efab..bce666d484 100644 --- a/crates/mcp/src/tests/shapewidgets.rs +++ b/crates/mcp/src/tests/shapewidgets.rs @@ -1,5 +1,6 @@ -//! A shape tool's double-click on a selected live shape's corner widget through MCP: the -//! gesture's `requests` carry the Transform panel. +//! Live shape widgets through MCP: a shape tool's double-click on a selected live shape's corner +//! widget, whose gesture's `requests` carry the Transform panel, and a drag on a live polygon's +//! side widget. use serde_json::{Value, json}; use vectorcraft_tools::corners::CornerWidgets; @@ -28,3 +29,74 @@ fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel() let off = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 280, "y": 280}]})); assert_eq!(off["requests"], json!([]), "{off}"); } + +/// The selected live polygon's sides, radius and transform. +fn polygon(h: &mut Headless) -> (u32, f64, vectorcraft_geom::Affine) { + let st = h.session.doc().unwrap(); + let id = st.selection.objects[0]; + let vectorcraft_doc::NodeKind::Path { live, .. } = &st.doc.node(id).unwrap().kind else { panic!("not a path") }; + let Some(vectorcraft_doc::LiveShape::Polygon { sides, radius, xf, .. }) = live.as_deref() else { panic!("not a live polygon: {live:?}") }; + (*sides, *radius, *xf) +} + +/// A drag down on a live polygon's side widget with the Selection tool gives it more sides in one +/// undo step, keeping its radius and transform; undo puts the count back. +#[test] +fn a_side_widget_drag_changes_a_polygons_sides_in_one_undo_step() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + h.call("engine.execute", json!({"command": "shape.polygon", "params": {"cx": 150, "cy": 150, "radius": 60, "sides": 5}})).unwrap(); + let st = h.session.doc().unwrap(); + let id = st.selection.objects[0]; + let b = st.doc.node(id).unwrap().geometric_bounds_with(&st.doc.symbol_boxes()).expect("bounds"); + let bx = vectorcraft_doc::OrientedBox::aligned(b); + let w = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &bx, h.view.zoom).expect("a side widget"); + let steps = st.history.undo.len(); + let before = polygon(&mut h); + assert_eq!(before.0, 5); + let zoom = h.view.zoom; + let ev = |kind: &str, dy: f64| json!({"kind": kind, "x": w.at.x, "y": w.at.y + dy / zoom}); + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 13.0), ev("drag", 25.0), ev("up", 25.0)]})); + let after = polygon(&mut h); + assert_eq!((after.0, after.1, after.2), (7, before.1, before.2)); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + h.call("engine.execute", json!({"command": "edit.undo", "params": {}})).unwrap(); + assert_eq!(polygon(&mut h), before); + // A drag that comes back to the start leaves no undo step. + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 25.0), ev("drag", 0.0), ev("up", 0.0)]})); + assert_eq!(polygon(&mut h), before); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps); +} + +/// A batch run during a side widget drag settles the drag first. A batch step that switches +/// documents then ends the drag without undoing the batch's own steps in the document it leaves. +#[test] +fn a_batch_that_switches_documents_during_a_side_widget_drag_keeps_its_steps() { + let mut h = Headless::new(); + for _ in 0..2 { + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + } + h.call("engine.execute", json!({"command": "shape.polygon", "params": {"cx": 150, "cy": 150, "radius": 60, "sides": 5}})).unwrap(); + let st = h.session.doc().unwrap(); + let (uid, id) = (st.uid, st.selection.objects[0]); + let b = st.doc.node(id).unwrap().geometric_bounds_with(&st.doc.symbol_boxes()).expect("bounds"); + let bx = vectorcraft_doc::OrientedBox::aligned(b); + let w = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &bx, h.view.zoom).expect("a side widget"); + let steps = st.history.undo.len(); + let zoom = h.view.zoom; + let ev = |kind: &str, dy: f64| json!({"kind": kind, "x": w.at.x, "y": w.at.y + dy / zoom}); + // The drag stays held: no `up`. + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 13.0), ev("drag", 25.0)]})); + let batch = json!({"commands": [ + {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 20, "height": 20}}, + {"command": "document.activate", "params": {"index": 0}} + ]}); + h.call("engine.execute", json!({"command": "command.batch", "params": batch})).unwrap(); + let st = h.session.documents().iter().find(|d| d.uid == uid).expect("the polygon's document"); + let vectorcraft_doc::NodeKind::Path { live, .. } = &st.doc.node(id).unwrap().kind else { panic!("not a path") }; + assert!(matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Polygon { sides: 7, .. })), "the settled drag: {live:?}"); + assert_eq!(st.history.undo.len(), steps + 2, "the drag and the batch, each one undo step"); + let rect = st.selection.objects[0]; + assert_ne!(rect, id, "the batch's rectangle is selected"); + assert!(st.doc.node(rect).is_some(), "the batch's rectangle stays"); +} diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 642f65fbfe..ce9cac1e02 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -8,6 +8,11 @@ fn num(desc: &str) -> Value { json!({"type": "number", "description": desc}) } +/// A number or null. +fn num_or_null(desc: &str) -> Value { + json!({"description": desc, "anyOf": [{"type": "number"}, {"type": "null"}]}) +} + fn string(desc: &str) -> Value { json!({"type": "string", "description": desc}) } @@ -470,16 +475,16 @@ pub fn tool_definitions() -> Vec { obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, - "dx": num("Move right"), - "dy": num("Move down"), - "rotate": num("Rotation in degrees counter-clockwise"), - "scale": num("Uniform scale in %"), - "scaleX": num("Horizontal scale in %"), - "scaleY": num("Vertical scale in %"), - "reflect": {"type": "string", "enum": ["vertical", "horizontal"]}, - "shear": num("Shear angle in degrees (horizontal axis: positive moves the top to the right, turning the vertical edges clockwise)"), - "origin": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, - "copy": {"type": "boolean"}, + "dx": num_or_null("Move right (null: 0)"), + "dy": num_or_null("Move down (null: 0)"), + "rotate": num_or_null("Rotation in degrees counter-clockwise"), + "scale": num_or_null("Uniform scale in %"), + "scaleX": num_or_null("Horizontal scale in %"), + "scaleY": num_or_null("Vertical scale in %"), + "reflect": {"anyOf": [{"type": "string", "enum": ["vertical", "horizontal"]}, {"type": "null"}]}, + "shear": num_or_null("Shear angle in degrees (horizontal axis: positive moves the top to the right, turning the vertical edges clockwise)"), + "origin": {"anyOf": [{"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, {"type": "null"}]}, + "copy": {"anyOf": [{"type": "boolean"}, {"type": "null"}]}, }), &[], ), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 1a526d915d..8e1da7dcf2 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -143,6 +143,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), + ( + "file.export.svg.browser", + "Show in Browser", + "", + "{svg?: {…SVG options}, exportSelection?} SVG Options' Show in Browser: write the SVG of one page (with exportSelection the selection's crop, else the first artboard the options choose) and its linked images to a new temporary folder and open it in the default browser (desktop; refused for control and MCP requests) → {path, warnings}", + ), ( "file.export.png", "Export As PNG…", @@ -184,8 +190,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+I", "{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options", ), - ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), - ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), + ( + "shortcuts.set", + "Set Keyboard Shortcut", + "", + "{id: command id or tool:, shortcut?: \"Cmd+Shift+K\" | \"\" (none) | null (default), hold?: a character key alone or with Shift (\"X\", \"Shift+X\", \".\") | \"\" | null (none), force?} → {id, shortcut, hold, removedFrom}; `hold` alone leaves the shortcut as it is; a command listed only with a shortcut takes a hold only with one and loses it with the shortcut; a hold shortcut acts while the holdShortcuts preference is on", + ), + ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, hold, default, overridden}]"), ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), ("shortcuts.reset", "Reset Keyboard Shortcuts", "", "{}"), ( @@ -199,7 +210,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", + "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none, and while the holdShortcuts preference is on a third `Hold ` column on a row with a hold shortcut. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( @@ -374,6 +385,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), + ( + "align.toSelection", + "Align to Selection", + "", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected, since one object aligns to the artboard}; with the Artboard tool chosen the selected objects keep their key", + ), + ( + "align.toKeyObject", + "Align to Key Object", + "", + "{} the Align panel's Align to Key Object button: with no key, the topmost of two or more selected objects becomes the key object, or a ruler guide selected with one object the key guide; the stored Selection or Artboard choice stays → {alignTo: \"key\"}; an error (\"no key object\") when there is no key and nothing to make one of, which includes a topmost selected object inside another selected object; an error (\"Align to Key Object isn't available with the Artboard tool\") with the Artboard tool chosen", + ), + ( + "align.toArtboard", + "Align to Artboard", + "", + "{} the Align panel's Align to Artboard button: Align To becomes Artboard (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: \"artboard\"}; with the Artboard tool chosen the selected objects keep their key", + ), ( "type.bold", "Bold", @@ -416,6 +445,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+Shift+U", "{} the Character panel's Underline button: underline the selected type (or the Type tool's selection), or remove the underline when the text the Character panel shows is underlined (text.setFormat {underline}) → underlined", ), + ( + "type.superscript", + "Superscript", + "Cmd+Shift+=", + "{} the Character panel's Superscript button: the selected type (or the Type tool's selection, all of its text at a caret) becomes superscript, or Normal when all of it is superscript already (text.setFormat {position}). Without selected type the keys zoom in, as Cmd+= does → \"superscript\" | \"normal\"", + ), + ( + "type.subscript", + "Subscript", + "Cmd+Alt+Shift+=", + "{} the Character panel's Subscript button: the selected type (or the Type tool's selection, all of its text at a caret) becomes subscript, or Normal when all of it is subscript already (text.setFormat {position}) → \"subscript\" | \"normal\"", + ), ( "type.lineComposer", "Toggle Line Composer", @@ -871,7 +912,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{effect: id, index?: int (edit that applied effect in place, prefilled; OK runs effect.setParams), item?: appearance item index|null (the fill/stroke whose effects, null the object's; default: the Appearance panel's active item), aligned?: bool (index and item are rows of the first selected object's stack, which OK edits in each object where it has them, as effect.setParams does)} open the effect's dialog with live preview; without `index`, an effect already in that list first opens `effectExists` (confirm edits it, discard adds another) → {pending: \"effectExists\"}", ), - ("ui.paramDialog", "Command Dialog", "", "{command, label?, params} open a parameter dialog for any command"), + ( + "ui.paramDialog", + "Command Dialog", + "", + "{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + ), ( "ui.recolorDialog", "Recolor Artwork…", @@ -1032,7 +1078,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1152,6 +1198,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), + ( + "ui.attributesPanelOptions", + "Panel Options…", + "", + "{count?: 1–30 (10 by default)} set how many of the recent URLs (attributes.info › recentUrls, which keeps 30) the Attributes panel's URL menu lists, newest first (kept with the UI state) → {count}; without count, open its Panel Options (dialog `attributesPanelOptions`, field count; OK sets it); an error for a count that is not a whole number from 1 to 30, which changes nothing", + ), ( "ui.layersExpand", "Expand Layers Panel Rows", @@ -1443,7 +1495,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, vision}", ), ( "ui.savePdfDialog", @@ -1520,6 +1572,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the export progress dialog; the exports go on, shown in the status bar → {hidden: n}", ), + ( + "file.cancelSave", + "Cancel Save", + "", + "{} stop every save running in the background (Background Save) before it replaces its file: the file stays as it was and the document keeps its file and stays modified; a save whose file was already being replaced finishes and is reported as saved → {cancelled: n}", + ), + ( + "file.saveInBackground", + "Continue in Background", + "", + "{} close the save progress window; the saves go on, shown in the status bar → {hidden: n}", + ), ( "file.cancelOpen", "Cancel Opening", @@ -1724,6 +1788,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", ), + ( + "ui.actionSet.clear", + "Clear Actions", + "", + "{ids?: [id]} Clear Actions: delete every set in the Actions panel with its actions, the built-in Default Actions set included, so no set is current or selected; the panel's selected action and step and its expanded actions are cleared, and an open Set Options, New Action, Batch or step dialog that names a set closes. ids holds the panel's own set ids in panel order, which the menu's question passes: when the sets are no longer exactly those, nothing is deleted. With no sets, nothing changes and cleared is 0. Omitted params count as {}. Params of another type, another key, ids that is not a list of ids, or a clear while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Clear Actions (disabled with no sets and while an action records or plays) asks first, and OK runs this → {cleared: the number of sets deleted}", + ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( "docInfo.save", diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 8e5f53ce41..3f6dd8d5dd 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -85,14 +85,23 @@ pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result Result<(), String> { + let empty = |r: Rect| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0; + if regions.iter().any(|r| empty(r.abs())) { + return Err("the export region is empty".into()); + } + Ok(()) +} + /// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the /// same order, each as [`export`] writes it over that region. The live effects are applied once /// for all of them. When any region is empty, nothing is written and the result is an error. pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, String> { + check_regions(regions)?; let regions: Vec = regions.iter().map(|r| r.abs()).collect(); - if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) { - return Err("the export region is empty".into()); - } if regions.is_empty() { return Ok(Vec::new()); } diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index d8ad6ae8e4..ed01ec3ce8 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,10 +4,10 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]), the common -//! tangents of two convex outlines ([`common_tangents`]), the -//! Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch two or three shapes -//! ([`tangent_circles`]). +//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]) or many circles +//! joined to their neighbors ([`bridge_many`]), the common tangents of two convex outlines +//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch +//! two or three shapes ([`tangent_circles`]). mod bridge; mod crossings; @@ -27,7 +27,9 @@ use std::collections::BTreeSet; use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2}; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; -pub use bridge::{BridgeError, circle_of, smooth_bridge}; +pub use bridge::{ + ArcRadius, BridgeError, Bridged, Joined, MAX_BRIDGED_CIRCLES, MAX_BRIDGES, ManyError, bridge_many, bridges_any, circle_of, smooth_bridge, +}; pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; diff --git a/crates/pathops/src/addons/pathtools/bridge.rs b/crates/pathops/src/addons/pathtools/bridge.rs index 43ee629a91..f0afa31dc8 100644 --- a/crates/pathops/src/addons/pathtools/bridge.rs +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -1,10 +1,14 @@ //! Smooth Bridge: two circles joined into one outline by two concave arcs, each touching both -//! circles from outside, so the outline runs on smoothly from each circle into the bridge. +//! circles from outside, so the outline runs on smoothly from each circle into the bridge; and +//! many circles joined at once, each to the others within reach ([`bridge_many`]). +use std::collections::{BTreeMap, HashMap, HashSet}; use std::f64::consts::{FRAC_PI_2, PI, SQRT_2, TAU}; use kurbo::{CubicBez, ParamCurve, Point, Shape, Vec2}; -use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; +use vectorcraft_geom::{Anchor, AnchorKind, FillRule, PathData, SubPath, shapes}; + +use crate::boolean::{DEFAULT_PRECISION, try_unite_all_with}; use super::Circle; @@ -58,6 +62,64 @@ pub fn circle_of(path: &PathData) -> Option { /// a tangent there. Overlapping and touching circles are joined too. A larger radius makes a wider, /// gentler bridge; farther apart circles make a narrower one, until the arcs would cross. pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result { + let t = touches(a, b, radius)?; + let mut segs = vec![]; + arc(&mut segs, a.center, a.radius, t.a1, t.a2, Some(-t.u)); + arc(&mut segs, t.p2, radius, t.a2, t.b2, None); + arc(&mut segs, b.center, b.radius, t.b2, t.b1, Some(t.u)); + arc(&mut segs, t.p1, radius, t.b1, t.a1, None); + closed(&segs, AnchorKind::Smooth) +} + +/// The part of [`smooth_bridge`]'s outline between the circles: the two arcs, joined across each +/// circle by a straight line between the arc ends on it. Each line lies inside its circle, so the +/// two circles and this shape unite into the outline, with each circle drawn once however many +/// bridges it has. +fn neck(a: Circle, b: Circle, radius: f64) -> Result { + let t = touches(a, b, radius)?; + let line = |p: Point, q: Point| CubicBez::new(p, p, q, q); + let mut segs = vec![]; + arc(&mut segs, t.p2, radius, t.a2, t.b2, None); + segs.push(line(t.b2, t.b1)); + arc(&mut segs, t.p1, radius, t.b1, t.a1, None); + segs.push(line(t.a1, t.a2)); + closed(&segs, AnchorKind::Corner) +} + +/// A closed subpath through the cubics `segs`, each starting where the one before it ends, with +/// anchors of `kind`; [`BridgeError::Bad`] when a point does not fit in `f64`. +fn closed(segs: &[CubicBez], kind: AnchorKind) -> Result { + let count = segs.len(); + let anchors: Vec = (0..count) + .filter_map(|i| { + let (prev, seg) = (segs.get((i + count - 1) % count)?, segs.get(i)?); + Some(Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind }) + }) + .collect(); + let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite(); + if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) { + return Err(BridgeError::Bad); + } + Ok(SubPath::new(anchors, true)) +} + +/// Where the arcs of radius `radius` that bridge circles `a` and `b` lie: the unit vector from +/// `a`'s center to `b`'s, and on each side the arc's center (`p1`, `p2`) and where it touches `a` +/// and `b`; and the neck's width where the arcs come nearest each other between the circles +/// (infinite when that is at the circles). +struct Touches { + waist: f64, + u: Vec2, + p1: Point, + a1: Point, + b1: Point, + p2: Point, + a2: Point, + b2: Point, +} + +/// The arcs of [`smooth_bridge`], or why there are none. +fn touches(a: Circle, b: Circle, radius: f64) -> Result { let finite = |x: f64| x.is_finite() && x > 0.0; let points = [a.center, b.center].iter().all(|c| c.x.is_finite() && c.y.is_finite()); if !finite(radius) || !finite(a.radius) || !finite(b.radius) || !points { @@ -95,29 +157,237 @@ pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result = (0..count) - .map(|i| { - let (prev, seg) = (segs[(i + count - 1) % count], segs[i]); - Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind: AnchorKind::Smooth } - }) - .collect(); - let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite(); - if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) { - return Err(BridgeError::Bad); + let waist = if along > 0.0 && along < d { 2.0 * (across - radius) } else { f64::INFINITY }; + Ok(Touches { waist, u, p1, a1, b1, p2, a2, b2 }) +} + +/// The most circles [`bridge_many`] takes. +pub const MAX_BRIDGED_CIRCLES: usize = 2000; +/// The most bridges [`bridge_many`] makes. +pub const MAX_BRIDGES: usize = 8000; +/// Holes [`bridge_many`] fills: those smaller than this share of the area of the smallest circle +/// they join. +const SPECK: f64 = 0.01; + +/// The radius of the arcs that bridge two circles. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ArcRadius { + /// This share of the smaller circle's radius (1 is the same radius). + Share(f64), + /// The smaller circle's radius plus this gap (pt). Each arc is then this gap outside a circle + /// of the smaller circle's radius about the arc's center: for equal circles that gap apart, + /// the place of a third circle that gap from both, as in a triangular grid. + Gap(f64), +} + +impl ArcRadius { + /// The arcs' radius (pt) for circles `a` and `b`. + pub fn between(self, a: Circle, b: Circle) -> f64 { + let r = a.radius.min(b.radius); + match self { + ArcRadius::Share(share) => r * share, + ArcRadius::Gap(gap) => r + gap, + } } - Ok(SubPath::new(anchors, true)) +} + +/// Circles that bridges join into one shape: their indices, ascending, and the shape's outline. +#[derive(Clone, Debug, PartialEq)] +pub struct Joined { + pub members: Vec, + pub outline: PathData, +} + +/// What [`bridge_many`] makes: the joined shapes, in the order of their first member, and the +/// indices of the circles left alone, ascending. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Bridged { + pub joined: Vec, + pub alone: Vec, +} + +/// Why [`bridge_many`] makes nothing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ManyError { + /// More than [`MAX_BRIDGED_CIRCLES`] circles. + TooManyCircles, + /// More than [`MAX_BRIDGES`] pairs of circles within reach that the arcs can bridge. + TooManyBridges, + /// No two circles are within reach of each other. + NoneInReach, + /// The circles at these indices are within reach but [`smooth_bridge`] can't join them: one is + /// inside the other, or no pair within reach is near enough for the arcs (the first such pair). + Pair(usize, usize, BridgeError), + /// A reach that is not a finite size of 0 or more, or a circle that is not a finite size above 0. + Bad, + /// A joined shape too complex to unite. + TooComplex, +} + +/// Every pair of `circles` whose outlines are at most `reach` (pt) apart, overlapping ones +/// included, joined by a [`smooth_bridge`] with arcs of radius `arc`, and the bridges that connect +/// united into one shape each, without holes smaller than 1% of the smallest circle's area. A pair +/// too far apart for the arcs gets no bridge; a circle bridged to no other is left alone. One +/// circle inside another is an error, and so is no pair that the arcs can join. +pub fn bridge_many(circles: &[Circle], arc: ArcRadius, reach: f64) -> Result { + let (pairs, too_far, roots, precision) = bridgeable(circles, arc, reach)?; + match (pairs.is_empty(), too_far) { + (true, Some((i, j))) => return Err(ManyError::Pair(i, j, BridgeError::TooFar)), + (true, None) => return Err(ManyError::NoneInReach), + (false, _) => {} + } + let mut necks = Vec::with_capacity(pairs.len()); + for &((i, j), _) in &pairs { + let (a, b) = (circles[i], circles[j]); + let sp = neck(a, b, arc.between(a, b)).map_err(|e| ManyError::Pair(i, j, e))?; + necks.push(((i, j), PathData::single(sp))); + } + let mut sets: BTreeMap, Vec<&PathData>)> = BTreeMap::new(); + for &((i, j), ref neck) in &necks { + let (members, parts) = sets.entry(roots[i]).or_default(); + members.extend([i, j]); + parts.push(neck); + } + let mut out = Bridged::default(); + for (set, (mut members, parts)) in sets { + members.sort_unstable(); + members.dedup(); + // Each circle once, and the necks between them. + let rounds: Vec = members + .iter() + .filter_map(|&i| circles.get(i)) + .map(|c| shapes::ellipse(kurbo::Rect::from_center_size(c.center, (2.0 * c.radius, 2.0 * c.radius)))) + .collect(); + let fills: Vec<(&PathData, FillRule)> = rounds.iter().chain(parts).map(|p| (p, FillRule::NonZero)).collect(); + let smallest = members.iter().filter_map(|&i| circles.get(i)).map(|c| c.radius).fold(f64::INFINITY, f64::min); + let mut outline = try_unite_all_with(&fills, precision[set]).map_err(|_| ManyError::TooComplex)?; + // Where three bridges' arcs nearly meet, the union leaves a speck of a hole; a contour that + // encloses a circle is far larger than this. + let speck = SPECK * PI * smallest * smallest; + outline.subpaths.retain(|sp| PathData::single(sp.clone()).to_bezpath().area().abs() >= speck); + out.joined.push(Joined { members, outline }); + } + let joined: HashSet = necks.iter().flat_map(|&((i, j), _)| [i, j]).collect(); + out.alone = (0..circles.len()).filter(|i| !joined.contains(i)).collect(); + Ok(out) +} + +/// Whether [`bridge_many`] would bridge at least one pair of `circles` with arcs of `arc` and +/// `reach`, under the same rules (a neck too thin for its shape's precision included), without +/// making the bridges or uniting them. +pub fn bridges_any(circles: &[Circle], arc: ArcRadius, reach: f64) -> bool { + bridgeable(circles, arc, reach).is_ok_and(|(pairs, ..)| !pairs.is_empty()) +} + +/// What [`bridgeable`] finds: the pairs [`bridge_many`] bridges with their necks' widths, the +/// lowest pair within reach that it can't bridge, each circle's set (its lowest index) and each +/// set's precision, under its lowest index. +type Bridgeable = (Vec<(Pair, f64)>, Option, Vec, Vec); + +/// The pairs of `circles` that [`bridge_many`] bridges, and how it sorts them into sets. +fn bridgeable(circles: &[Circle], arc: ArcRadius, reach: f64) -> Result { + if circles.len() > MAX_BRIDGED_CIRCLES { + return Err(ManyError::TooManyCircles); + } + let fine = |c: &Circle| c.center.x.is_finite() && c.center.y.is_finite() && c.radius.is_finite() && c.radius > 0.0; + if !(reach.is_finite() && reach >= 0.0) || !circles.iter().all(fine) { + return Err(ManyError::Bad); + } + let (mut pairs, mut too_far) = pairs_within(circles, reach, arc)?; + // Each set of connected circles, under its lowest index, is united at a precision fine enough + // for its smallest circle. A neck narrower than twice that would not survive the union, so its + // pair gets no bridge; that can split a set and make its precision coarser, so the sets are + // found again until no neck is dropped. + let (roots, precision) = loop { + let mut parent: Vec = (0..circles.len()).collect(); + for &((i, j), _) in &pairs { + let (ri, rj) = (root(&mut parent, i), root(&mut parent, j)); + parent[ri.max(rj)] = ri.min(rj); + } + let roots: Vec = (0..circles.len()).map(|i| root(&mut parent, i)).collect(); + let mut precision = vec![DEFAULT_PRECISION; circles.len()]; + for (&r, c) in roots.iter().zip(circles) { + precision[r] = precision[r].min(c.radius * 1e-3); + } + let thin = |&((i, _), waist): &(Pair, f64)| waist < 2.0 * precision[roots[i]]; + if !pairs.iter().any(thin) { + break (roots, precision); + } + for &(pair, _) in pairs.iter().filter(|&p| thin(p)) { + too_far = Some(too_far.map_or(pair, |t| t.min(pair))); + } + pairs.retain(|p| !thin(p)); + }; + Ok((pairs, too_far, roots, precision)) +} + +/// Two circles' indices, the lower first. +type Pair = (usize, usize); +/// What [`pairs_within`] finds: the pairs the arcs can bridge, each with its neck's width, and the +/// lowest pair too far apart for them. +type Within = (Vec<(Pair, f64)>, Option); + +/// The set `i` is in: the lowest index in it, with the path to it shortened on the way. +fn root(parent: &mut [usize], mut i: usize) -> usize { + while parent[i] != i { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + i +} + +/// Every pair of indices `(i, j)`, `i < j`, ascending, of `circles` whose outlines are at most +/// `reach` apart and that arcs of `arc` can bridge, with the width of the neck between them, and +/// the lowest pair within reach that they can't because it is too far apart for them. Circles go +/// into a grid of cells as wide as the farthest two centers within reach can be, so each circle is +/// compared only with those in its own cell and the eight around it. +fn pairs_within(circles: &[Circle], reach: f64, arc: ArcRadius) -> Result { + let biggest = circles.iter().map(|c| c.radius).fold(0.0, f64::max); + let cell = 2.0 * biggest + reach; + if !(cell.is_finite() && cell > 0.0) { + return Err(ManyError::Bad); + } + // Saturating casts: a cell beyond i64 shares the last one, which only adds comparisons. + let key = |p: Point| ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64); + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, c) in circles.iter().enumerate() { + grid.entry(key(c.center)).or_default().push(i); + } + let (mut pairs, mut too_far) = (vec![], None::); + for (i, &c) in circles.iter().enumerate() { + let (x, y) = key(c.center); + for (dx, dy) in (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (dx, dy))) { + let Some(near) = grid.get(&(x.saturating_add(dx), y.saturating_add(dy))) else { continue }; + for &j in near.iter().filter(|&&j| j > i) { + let o = circles[j]; + if c.center.distance(o.center) - c.radius - o.radius > reach { + continue; + } + // Only the arcs' ends are worked out here; the bridge itself is made later. + match touches(c, o, arc.between(c, o)) { + Ok(t) => pairs.push(((i, j), t.waist)), + Err(BridgeError::TooFar) => too_far = Some(too_far.map_or((i, j), |t| t.min((i, j)))), + Err(e) => return Err(ManyError::Pair(i, j, e)), + } + } + } + // Saturated cells can list a pair twice, so the count is checked again after `dedup`. + if pairs.len() > 9 * MAX_BRIDGES { + return Err(ManyError::TooManyBridges); + } + } + pairs.sort_unstable_by_key(|&(pair, _)| pair); + pairs.dedup_by_key(|&mut (pair, _)| pair); + if pairs.len() > MAX_BRIDGES { + return Err(ManyError::TooManyBridges); + } + Ok((pairs, too_far)) } /// Append to `out` the arc of the circle about `center` with radius `r` from `from` to `to` (both @@ -331,6 +601,198 @@ mod tests { assert_eq!(smooth_bridge(circle(f64::INFINITY, 0.0, 10.0), b, 10.0), Err(BridgeError::Bad)); } + /// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), top-left at the origin. + fn grid() -> Vec { + (0..9).map(|k| circle(24.0 * (k % 3) as f64, 24.0 * (k / 3) as f64, 10.0)).collect() + } + + fn area(path: &PathData) -> f64 { + crate::area(path, FillRule::NonZero) + } + + fn inside(path: &PathData, x: f64, y: f64) -> bool { + path.to_bezpath().winding(Point::new(x, y)) != 0 + } + + #[test] + fn a_grid_joins_each_circle_to_its_neighbors_within_reach() { + // Reach 5: the side neighbors (4 apart) are joined, the diagonal ones (about 13.9 apart) not. + let b = bridge_many(&grid(), ArcRadius::Gap(4.0), 5.0).unwrap(); + assert_eq!(b.alone, Vec::::new()); + let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) }; + assert_eq!(one.members, (0..9).collect::>()); + for (x, y) in [(12.0, 0.0), (0.0, 12.0), (36.0, 48.0), (48.0, 36.0), (24.0, 24.0)] { + assert!(inside(&one.outline, x, y), "bridged at ({x}, {y})"); + } + // Between four circles the side bridges' arcs leave a hole: no diagonal bridge fills it. + for (x, y) in [(12.0, 12.0), (36.0, 36.0)] { + assert!(!inside(&one.outline, x, y), "a hole at ({x}, {y})"); + } + let hull = PathData::single(SubPath::polyline( + &[Point::new(-10.0, -10.0), Point::new(58.0, -10.0), Point::new(58.0, 58.0), Point::new(-10.0, 58.0)], + true, + )); + assert!(area(&one.outline) < area(&hull)); + assert_eq!(one.outline.subpaths.len(), 5, "the outline and a hole in each square"); + // Reach 15 takes in the diagonal neighbors too, and their bridges fill the middle of each + // square. The specks of holes (about 0.1 pt²) where side and diagonal arcs nearly meet are + // filled. + let b = bridge_many(&grid(), ArcRadius::Gap(4.0), 15.0).unwrap(); + let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) }; + assert!(inside(&one.outline, 12.0, 12.0) && inside(&one.outline, 36.0, 36.0)); + assert_eq!(one.outline.subpaths.len(), 1); + } + + #[test] + fn a_circle_with_no_neighbor_in_reach_is_left_alone() { + let mut circles = grid(); + circles.truncate(2); + circles.push(circle(200.0, 0.0, 10.0)); + circles.push(circle(224.0, 0.0, 10.0)); + circles.push(circle(100.0, 100.0, 10.0)); + let b = bridge_many(&circles, ArcRadius::Share(1.0), 5.0).unwrap(); + assert_eq!(b.joined.iter().map(|j| j.members.clone()).collect::>(), [vec![0, 1], vec![2, 3]]); + assert_eq!(b.alone, [4]); + // Each pair alone is the two-circle bridge. + let two = smooth_bridge(circles[0], circles[1], 10.0).unwrap(); + let (got, want) = (area(&b.joined[0].outline), area(&PathData::single(two))); + assert!((got - want).abs() < 1e-3 * want, "{got} {want}"); + } + + #[test] + fn a_ring_around_an_empty_place_leaves_a_round_hole_the_gap_wider_than_a_circle() { + // Six circles of radius 10 around an empty place at the origin, each 4 from its two + // neighbors and from where a seventh circle would be (centers 24 from the origin). + let ring: Vec = (0..6).map(|k| f64::from(k) * PI / 3.0).map(|t| circle(24.0 * t.cos(), 24.0 * t.sin(), 10.0)).collect(); + let b = bridge_many(&ring, ArcRadius::Gap(4.0), 5.0).unwrap(); + let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) }; + assert_eq!(one.members, (0..6).collect::>()); + assert_eq!(one.outline.subpaths.len(), 2, "the outline and the hole"); + // The hole's edge is 14 from the origin all the way round: a circle of radius 10 there + // would be 4 from the shape everywhere, the same as from each of the six. + let hole = one.outline.subpaths.iter().min_by(|p, q| { + let size = |sp: &SubPath| PathData::single(sp.clone()).to_bezpath().area().abs(); + size(p).total_cmp(&size(q)) + }); + let edge = outline(hole.unwrap()); + let (near, far) = edge.iter().map(|p| p.distance(Point::ZERO)).fold((f64::INFINITY, 0.0f64), |(n, f), d| (n.min(d), f.max(d))); + assert!((near - 14.0).abs() < 1e-2 && (far - 14.0).abs() < 1e-2, "{near} to {far}"); + } + + #[test] + fn many_circles_make_the_two_circle_outline_for_each_pair() { + // Overlapping, touching, unequal and unequal overlapping pairs, each with a far circle. + for (a, b, share) in [ + (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 20.0), 0.5), + (circle(0.0, 0.0, 20.0), circle(40.0, 0.0, 20.0), 0.5), + (circle(0.0, 0.0, 30.0), circle(70.0, 0.0, 10.0), 4.0), + (circle(0.0, 0.0, 10.0), circle(25.0, 0.0, 30.0), 10.0), + // Circles far smaller than the union's usual precision (0.01 pt). + (circle(0.0, 0.0, 0.004), circle(0.01, 0.0, 0.004), 1.0), + ] { + let made = bridge_many(&[a, b, circle(1000.0, 0.0, 5.0)], ArcRadius::Share(share), 40.0).unwrap(); + assert_eq!(made.alone, [2]); + let two = smooth_bridge(a, b, share * a.radius.min(b.radius)).unwrap(); + let (got, want) = (area(&made.joined[0].outline), area(&PathData::single(two))); + assert!((got - want).abs() < 1e-3 * want, "{a:?}: {got} {want}"); + } + } + + #[test] + fn a_pair_too_far_apart_for_the_arcs_gets_no_bridge() { + // b and c are within reach (6 apart) but arcs of radius 3 close before they reach both. + let (a, b, c) = (circle(0.0, 0.0, 3.0), circle(8.0, 0.0, 3.0), circle(20.0, 0.0, 3.0)); + assert_eq!(smooth_bridge(b, c, 3.0), Err(BridgeError::TooFar)); + let made = bridge_many(&[a, b, c], ArcRadius::Share(1.0), 10.0).unwrap(); + assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::>(), [vec![0, 1]]); + assert_eq!(made.alone, [2]); + // Arcs of radius 10 between circles of radius 10 just under 20√3 apart leave a neck about + // 0.00003 pt wide, too thin for the union: that pair is left unbridged too. + let (a, b, c) = (circle(0.0, 0.0, 10.0), circle(34.6409, 0.0, 10.0), circle(58.6409, 0.0, 10.0)); + assert!(smooth_bridge(a, b, 10.0).is_ok(), "two circles alone are bridged"); + let made = bridge_many(&[a, b, c], ArcRadius::Share(1.0), 20.0).unwrap(); + assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::>(), [vec![1, 2]]); + assert_eq!(made.alone, [0]); + // Two tiny circles far off are united at a finer precision, which does not change that. + let tiny = [circle(500.0, 0.0, 0.01), circle(500.025, 0.0, 0.01)]; + let made = bridge_many(&[a, b, c, tiny[0], tiny[1]], ArcRadius::Share(1.0), 20.0).unwrap(); + assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::>(), [vec![1, 2], vec![3, 4]]); + assert_eq!(made.alone, [0]); + // 260 touching circles in a row with a wide reach: 33,670 pairs within reach, far more than + // the bridge limit, but only the 259 touching pairs are near enough for the arcs. + let row: Vec = (0..260).map(|i| circle(f64::from(i) * 20.0, 0.0, 10.0)).collect(); + let made = bridge_many(&row, ArcRadius::Share(1.0), 6000.0).unwrap(); + let [one] = made.joined.as_slice() else { panic!("{} shapes", made.joined.len()) }; + assert_eq!(one.members.len(), 260); + assert!(made.alone.is_empty()); + } + + #[test] + fn the_gap_form_keeps_the_gap_from_a_circle_at_each_arcs_center() { + // Two circles 4 apart; with a gap of 4 each arc's center is 24 from both centers, where a + // third circle of the same size is 4 from both (as in a triangular grid). + let (a, b) = (circle(0.0, 0.0, 10.0), circle(24.0, 0.0, 10.0)); + let r = ArcRadius::Gap(4.0).between(a, b); + assert_eq!(r, 14.0); + let sp = smooth_bridge(a, b, r).unwrap(); + for third in [circle(12.0, 432f64.sqrt(), 10.0), circle(12.0, -(432f64.sqrt()), 10.0)] { + let gaps: Vec = outline(&sp).iter().map(|p| p.distance(third.center) - third.radius).collect(); + // No part of the bridge comes nearer than the gap, and a stretch of it is that gap away. + assert!(gaps.iter().all(|&g| g > 4.0 - 1e-2), "{:?}", gaps.iter().copied().fold(f64::INFINITY, f64::min)); + let along = gaps.iter().filter(|&&g| (g - 4.0).abs() < 1e-2).count(); + assert!(along >= 32, "{along}"); + } + // The same for unequal circles: the gap is kept from a circle of the smaller one's size. + let (a, b) = (circle(0.0, 0.0, 15.0), circle(30.0, 5.0, 8.0)); + let r = ArcRadius::Gap(3.0).between(a, b); + let sp = smooth_bridge(a, b, r).unwrap(); + let d = (b.center - a.center).hypot(); + let (ra, rb) = (15.0 + r, 8.0 + r); + let along = (d * d + ra * ra - rb * rb) / (2.0 * d); + let u = (b.center - a.center) / d; + let center = a.center + u * along + Vec2::new(-u.y, u.x) * (ra * ra - along * along).sqrt(); + let gaps: Vec = outline(&sp).iter().map(|p| p.distance(center) - 8.0).collect(); + assert!(gaps.iter().all(|&g| g > 3.0 - 1e-2) && gaps.iter().filter(|&&g| (g - 3.0).abs() < 1e-2).count() >= 16); + } + + #[test] + fn the_gap_form_is_the_percentage_form_of_the_radius_plus_the_gap() { + for (a, b, gap) in [(circle(0.0, 0.0, 10.0), circle(24.0, 0.0, 10.0), 4.0), (circle(0.0, 0.0, 20.0), circle(40.0, 30.0, 10.0), 7.5)] { + let small = a.radius.min(b.radius); + let share = ArcRadius::Share((small + gap) / small); + assert!((ArcRadius::Gap(gap).between(a, b) - share.between(a, b)).abs() < 1e-12); + let (g, s) = (smooth_bridge(a, b, ArcRadius::Gap(gap).between(a, b)).unwrap(), smooth_bridge(a, b, share.between(a, b)).unwrap()); + for (p, q) in g.anchors.iter().zip(&s.anchors) { + assert!(p.p.distance(q.p) < 1e-9 && p.h_in.distance(q.h_in) < 1e-9 && p.h_out.distance(q.h_out) < 1e-9); + } + assert_eq!(g.anchors.len(), s.anchors.len()); + } + // Over a grid the two forms make the same shape too. + let by_gap = bridge_many(&grid(), ArcRadius::Gap(4.0), 5.0).unwrap(); + let by_share = bridge_many(&grid(), ArcRadius::Share(1.4), 5.0).unwrap(); + let (g, s) = (area(&by_gap.joined[0].outline), area(&by_share.joined[0].outline)); + assert!((g - s).abs() < 1e-6 * g, "{g} {s}"); + } + + #[test] + fn too_many_circles_or_bridges_and_bad_pairs_are_refused() { + let many = vec![circle(0.0, 0.0, 1.0); MAX_BRIDGED_CIRCLES + 1]; + assert_eq!(bridge_many(&many, ArcRadius::Share(1.0), 1.0), Err(ManyError::TooManyCircles)); + // 200 circles in a tight row: 19,900 pairs within reach. + let row: Vec = (0..200).map(|i| circle(i as f64 * 0.1, 0.0, 10.0)).collect(); + assert_eq!(bridge_many(&row, ArcRadius::Share(1.0), 1.0), Err(ManyError::TooManyBridges)); + let spread: Vec = (0..3).map(|i| circle(i as f64 * 100.0, 0.0, 10.0)).collect(); + assert_eq!(bridge_many(&spread, ArcRadius::Share(1.0), 5.0), Err(ManyError::NoneInReach)); + let nested = [circle(0.0, 0.0, 30.0), circle(5.0, 0.0, 10.0), circle(200.0, 0.0, 10.0)]; + assert_eq!(bridge_many(&nested, ArcRadius::Share(1.0), 5.0), Err(ManyError::Pair(0, 1, BridgeError::Inside))); + // Within reach (40 apart) but too far for arcs of radius 1. + let far = [circle(0.0, 0.0, 10.0), circle(60.0, 0.0, 10.0), circle(300.0, 0.0, 10.0)]; + assert_eq!(bridge_many(&far, ArcRadius::Share(0.1), 50.0), Err(ManyError::Pair(0, 1, BridgeError::TooFar))); + assert_eq!(bridge_many(&far, ArcRadius::Share(1.0), f64::NAN), Err(ManyError::Bad)); + assert_eq!(bridge_many(&far, ArcRadius::Share(1.0), -1.0), Err(ManyError::Bad)); + assert_eq!(bridge_many(&[circle(f64::INFINITY, 0.0, 1.0), far[0]], ArcRadius::Share(1.0), 1.0), Err(ManyError::Bad)); + } + #[test] fn huge_circles_bridge_with_finite_anchors_or_are_refused() { // Squaring these lengths overflows f64. diff --git a/crates/pdf/src/import/actual_text.rs b/crates/pdf/src/import/actual_text.rs index aec147f99e..aa7f9a5e76 100644 --- a/crates/pdf/src/import/actual_text.rs +++ b/crates/pdf/src/import/actual_text.rs @@ -1,6 +1,6 @@ //! Bounded ownership of authored replacement text (ISO 32000-1, 14.9.4). -use super::state::Builder; +use super::state::{Builder, HeldStroke}; use super::{Affine, Look, Placement, Shape, TextLine, Upright}; use crate::import_text::TextContent; @@ -21,13 +21,16 @@ impl ActualText { self.depth = self.depth.saturating_add(1); } - pub(super) fn end(&mut self) { - if self.owner == Some(self.depth) { + /// `true`: the owner's span ended. + pub(super) fn end(&mut self) -> bool { + let ended = self.owner == Some(self.depth); + if ended { self.owner = None; self.pending = None; self.empty = false; } self.depth = self.depth.saturating_sub(1); + ended } pub(super) fn active(&self) -> bool { @@ -62,13 +65,32 @@ impl Builder<'_> { /// against the glyph's original Unicode, not against this replacement's characters. pub(super) fn actual_glyph(&mut self, o: &craft_pdf::interpret::font::OutlineGlyph, m: Affine, at: Placement, look: Look, opacity: f32) -> bool { let key = o.font_cache_key(); - self.flush_glyphs(); - // A fill and stroke callback for the same glyph consumes its text only once. - if let (Some(stroke), Some(line)) = (&look.stroke, &mut self.text) - && look.fill.is_none() - && line.stroke_actual(key, at, stroke.clone(), look.overprint_stroke) + // A fill and stroke callback for the same glyph consumes its text only once: the stroke + // goes over the glyph of the span filled, matched as the stroke pass ends as any other + // (`Builder::hold_stroke`), on a line the operator's kerning finished too. + let stroking = look.fill.is_none() && look.stroke.is_some(); + if let Some(stroke) = &look.stroke + && stroking { - return true; + let h = HeldStroke { + font: key, + at, + opacity, + text: String::new(), + stroke: stroke.clone(), + overprint: look.overprint_stroke, + glyph: None, + actual: true, + first: (0, 0), + }; + if self.hold_stroke(h) { + return true; + } + } + self.flush_glyphs(); + // Stroked type of its own ends the stroke pass of the glyphs filled before it. + if stroking { + self.end_fills(); } let width = o.advance_width().filter(|w| w.is_finite()); let advance = width.map_or(at.size * 0.5, |w| w as f64 / 1000.0 * at.size * at.h_scale / 100.0); @@ -87,7 +109,7 @@ impl Builder<'_> { None => line.push_content(&look, at, opacity, advance, content), }; if !self.text.as_mut().is_some_and(place) { - self.flush_text(); + self.park_text(!stroking); let mut line = TextLine::new(at, opacity); if !place(&mut line) { self.actual.pending = pending; diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index eb8742f2db..b94350605a 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -4,7 +4,9 @@ use super::entry::{ UNNAMED_CHARACTERS_NOTE, max_objects, }; use super::reshaped; -use super::state::{Builder, Frame, FrameKind, GlyphRun, Saved, bounds, grouped, mean_scale, paints, round3, same_stroke, stroke_layer, type_stroke}; +use super::state::{ + Builder, Frame, FrameKind, GlyphRun, HeldStroke, Saved, bounds, grouped, mean_scale, paints, round3, same_stroke, stroke_layer, type_stroke, +}; use super::{ Affine, Appearance, AppearanceItem, Arc, BezPath, BfString, BlendMode, CacheKey, Color, Colors, Families, FillLayer, FillRule, FunctionBudget, FunctionPaint, HashMap, HashSet, ImageBlob, ImageObject, Knockout, Look, MaskSpec, MaskType, Native, Node, NodeId, NodeKind, OpacityMask, Paint, @@ -12,6 +14,30 @@ use super::{ Upright, Walked, clipped, contains, fold_stop_opacity, function_paint, gradient_shape, is_rectangle, luminance, mask_spec, shading_gradient, }; +/// The most lines of type kept for a text-showing operator's stroke pass ([`Builder::park_text`]): +/// beyond them the oldest is finished, and strokes over its glyphs come in as type of their own. +/// They are the lines its fill pass finished, besides the open one: a `TJ` over up to 65 lines is +/// filled and stroked, one over more is a filled object and a stroked one for each part. The +/// pass's first stroke goes over a glyph finished so, which can match a glyph kept (a `TJ` that +/// draws it again where it began): a first stroke that may go over one of them is type of its own +/// too, and ends the pass ([`Builder::hold_stroke`]). +const MAX_PARKED: usize = 64; + +/// The most strokes of a stroke pass held to be matched to the glyphs they go over +/// ([`Builder::hold_stroke`]): beyond them, those held are matched to the last glyphs filled one +/// after another that they go over, with as many glyphs filled from there on as strokes held +/// ([`Builder::replayed`]), and the pass goes on from there. The reader tells no operator's +/// start, so the last such run is taken: the operator's fill pass is the one right before its +/// stroke pass. An operator that fills the same run of more than this many glyphs twice at the +/// same places may have its first strokes matched to its second copy; such a pass is matched as +/// well as it can be, not exactly. +const MAX_HELD: usize = 4096; + +/// The most glyphs [`Builder::replayed`] compares to the strokes held, for bounded work on +/// hostile input: beyond them, each stroke goes over the first glyph it may go over after the one +/// the stroke before it goes over. +const MAX_REPLAY_WORK: usize = 1 << 20; + fn is_colour_face(face: &vectorcraft_text::FontFace) -> bool { use skrifa::Tag; use skrifa::raw::TableProvider; @@ -37,6 +63,9 @@ impl<'p> Builder<'p> { type3_run: None, text: None, text_glyphs: vec![], + parked: vec![], + held: vec![], + lost: None, text_as, actual: Default::default(), images: HashMap::new(), @@ -119,6 +148,9 @@ impl<'p> Builder<'p> { self.type3_run = None; self.text = None; self.text_glyphs.clear(); + self.parked.clear(); + self.held.clear(); + self.lost = None; self.mask = None; self.masked.clear(); self.marked.clear(); @@ -420,7 +452,10 @@ impl<'p> Builder<'p> { } } + /// Finish the open run of glyphs kept as outlines, once the strokes held are matched + /// ([`Self::settle_strokes`]): whatever is drawn next ends their stroke pass. pub(super) fn flush_glyphs(&mut self) { + self.settle_strokes(); let Some(run) = self.glyphs.take() else { return }; if run.path.elements().is_empty() { return; @@ -450,11 +485,274 @@ impl<'p> Builder<'p> { } } - /// Finish the open line of type. `true`: it was kept as outlines instead ([`reshaped`]), which - /// are left open as the glyph run for an outline drawn next to join. + /// Finish the open line of type, after the lines parked before it ([`Self::park_text`]). + /// `true`: the open line was kept as outlines instead ([`reshaped`]), which are left open as + /// the glyph run for an outline drawn next to join. pub(super) fn end_text(&mut self) -> bool { + self.settle_strokes(); + self.release_parked(usize::MAX); let glyphs = std::mem::take(&mut self.text_glyphs); - let Some(mut line) = self.text.take() else { return false }; + let Some(line) = self.text.take() else { return false }; + self.end_line(line, glyphs) + } + + /// Finish the first `n` parked lines ([`Self::park_text`]), in the order they were drawn. + pub(super) fn release_parked(&mut self, n: usize) { + let n = n.min(self.parked.len()); + if n == 0 { + return; + } + let lines: Vec<_> = self.parked.drain(..n).collect(); + for (line, glyphs) in lines { + if self.end_line(line, glyphs) { + self.flush_glyphs(); + } + } + } + + /// The open line ends where glyph drawn next starts another. The reader fills every glyph of + /// a text-showing operator before it strokes them (fill and stroke rendering): a line that a + /// stroke may still be drawn over is parked instead of finished, so that the operator's + /// stroke pass still finds the glyphs it filled when its kerning started a new line part way + /// through (#8543). Any other line, or with `park` false, is finished with the lines parked + /// before it. + /// + /// Parked lines are finished, oldest first, when the stroke pass goes past them (a stroke is + /// drawn over a later line or the open one: [`Self::settle_strokes`]; or over none of them: + /// [`Self::end_fills`]), when anything else ends the open line ([`Self::end_text`]), and + /// beyond [`MAX_PARKED`] lines: the glyphs of those are kept for the stroke after them + /// ([`Self::hold_stroke`]). + pub(super) fn park_text(&mut self, park: bool) { + match self.text.take() { + Some(line) if park && line.awaits_stroke() => { + let glyphs = std::mem::take(&mut self.text_glyphs); + self.parked.push((line, glyphs)); + let over = self.parked.len().saturating_sub(MAX_PARKED); + if over > 0 { + let lost = self.lost.get_or_insert_default(); + for (line, _) in self.parked.iter().take(over) { + lost.add(line); + } + } + self.release_parked(over); + } + line => { + self.text = line; + self.flush_text(); + } + } + } + + /// A boundary of stroke passes: no stroke drawn from now on goes over a glyph filled before + /// it. The strokes held are matched ([`Self::settle_strokes`]), the parked lines finished, and + /// the open line's glyphs filled so far closed to strokes ([`TextLine::end_fills`]). A stroke + /// that goes over no glyph filled (stroked type of its own) is one: a stroke pass replays the + /// glyphs its operator filled last, so a stroke after it isn't part of a pass over glyphs + /// filled before it, and stroking those would draw it under the type of its own. The start + /// and end of an ActualText span are too: a span's glyphs are stroked within it (#8543). + pub(super) fn end_fills(&mut self) { + self.lost = None; + self.settle_strokes(); + self.release_parked(usize::MAX); + if let Some(line) = &mut self.text { + line.end_fills(); + } + } + + /// The parked line at `slot` ([`Self::park_text`]), or the open line at the slot after them. + fn line_at(&self, slot: usize) -> Option<&TextLine> { + match self.parked.get(slot) { + Some((line, _)) => Some(line), + None if slot == self.parked.len() => self.text.as_ref(), + None => None, + } + } + + /// The glyph filled right after the one at `at` (a line's slot and its index among the line's + /// filled glyphs, as [`Self::next_fill`]): the next on its line, else the first of the line + /// after it. + fn after_fill(&self, (slot, i): (usize, usize)) -> (usize, usize) { + match self.line_at(slot) { + Some(line) if i.saturating_add(1) < line.filled_len() => (slot, i.saturating_add(1)), + _ => (slot.saturating_add(1), 0), + } + } + + /// The first glyph filled after `after` that stroke `h` may go over + /// ([`TextLine::next_filled`]), as its line's slot ([`Self::line_at`]) and its index among + /// the line's filled glyphs: the lines in the order they were drawn, each line's glyphs in + /// the order they were filled. From the first glyph with no `after`. + fn next_fill(&self, after: Option<(usize, usize)>, h: &HeldStroke) -> Option<(usize, usize)> { + let first = after.map_or(0, |(slot, _)| slot); + (first..=self.parked.len()).find_map(|slot| { + let from = match after { + Some((s, i)) if s == slot => i.saturating_add(1), + _ => 0, + }; + let i = self.line_at(slot)?.next_filled(from, h.font, h.at, h.opacity, &h.text, h.actual)?; + Some((slot, i)) + }) + } + + /// The last glyph filled before `before` that stroke `h` may go over ([`Self::next_fill`]). + /// From the last glyph with no `before`. + fn last_fill(&self, before: Option<(usize, usize)>, h: &HeldStroke) -> Option<(usize, usize)> { + let last = before.map_or(self.parked.len(), |(slot, _)| slot); + (0..=last).rev().find_map(|slot| { + let until = match before { + Some((s, i)) if s == slot => i, + _ => usize::MAX, + }; + let i = self.line_at(slot)?.last_filled(until, h.font, h.at, h.opacity, &h.text, h.actual)?; + Some((slot, i)) + }) + } + + /// Hold stroke `h`, over a glyph filled on the open line or a parked one, until its stroke + /// pass ends ([`Self::settle_strokes`]). `false`: no glyph filled after those the strokes + /// held go over is one it may go over (the strokes held are matched first, and if it may go + /// over none then, it isn't held either: it goes over the line as it stands). + /// + /// The reader fills all the glyphs of a text-showing operator, then strokes the same glyphs + /// in the same order (fill and stroke rendering, #8015). Which glyph a stroke goes over is + /// only told once the pass has ended: a `TJ` can draw the same glyph at the same place twice + /// (its kerning goes back), and an operator can fill and stroke a glyph where one filled + /// before it stands, which the device can't tell from a glyph the operator filled (#8543). + /// + /// The first stroke after lines were finished beyond [`MAX_PARKED`] ([`Self::park_text`]) + /// that may go over a glyph of theirs may be the start of their stroke pass, which no longer + /// finds its first glyphs: it ends the pass ([`Self::end_fills`]) and is type of its own, as + /// are the pass's strokes after it. Any other first stroke there is matched as ever: no + /// stroke pass is due over those lines once another stroke is drawn. + pub(super) fn hold_stroke(&mut self, mut h: HeldStroke) -> bool { + if self.lost.take().is_some_and(|lost| lost.may_stroke(h.font, h.at, h.opacity, &h.text, h.actual)) { + self.end_fills(); + return false; + } + if self.held.len() >= MAX_HELD { + self.settle(false); + } + let mut first = self.next_fill(self.held.last().map(|l| l.first), &h); + if first.is_none() && !self.held.is_empty() { + self.settle_strokes(); + first = self.next_fill(None, &h); + } + let Some(first) = first else { return false }; + h.first = first; + self.held.push(h); + true + } + + /// Match the strokes held ([`Self::hold_stroke`]) to the glyphs they go over, now that their + /// stroke pass has ended, and stroke them. The pass strokes the glyphs filled last, in the + /// order they were filled: each stroke goes over the last glyph it may go over that is filled + /// before the one the stroke after it goes over. So a `TJ` that draws a glyph twice at the + /// same place strokes each where it filled it, and a glyph filled and stroked where one + /// filled before it stands strokes the one filled last (#8015, #8543). + pub(super) fn settle_strokes(&mut self) { + self.settle(true); + } + + /// The glyphs the strokes `held` go over when they are the start of a stroke pass that goes + /// on after them ([`MAX_HELD`]): the last glyphs filled one right after another that they + /// may go over, in order, with at least as many glyphs filled from the first of them on as + /// there are strokes held. The pass replays its operator's fill pass, the glyphs filled + /// last, one right after another, right before the pass, so the strokes don't go over a + /// glyph filled before those, nor skip one. The device isn't told where an operator starts: + /// an operator before it that filled the same glyphs at the same places stays unstroked, as + /// the first glyphs of the pass are the last such run the pass still has room for. `None` + /// when there are none, or beyond [`MAX_REPLAY_WORK`]. + fn replayed(&self, held: &[HeldStroke]) -> Option> { + let (head, rest) = held.split_first()?; + let mut work = 0usize; + // The glyphs filled from `at` on, up to as many as there are strokes held. + let left = |(slot, i): (usize, usize)| { + (slot..=self.parked.len()) + .filter_map(|s| self.line_at(s).map(|line| line.filled_len().saturating_sub(if s == slot { i } else { 0 }))) + .fold(0usize, |n, len| n.saturating_add(len).min(held.len())) + }; + let mut start = self.last_fill(None, head); + while let Some(first) = start { + start = self.last_fill(Some(first), head); + work = work.saturating_add(1); + if work > MAX_REPLAY_WORK { + return None; + } + // Too few glyphs filled after it for the strokes held: not where the pass starts. + if left(first) < held.len() { + continue; + } + let mut places = Vec::with_capacity(held.len()); + places.push(first); + let mut at = first; + for h in rest { + work = work.saturating_add(1); + if work > MAX_REPLAY_WORK { + return None; + } + at = self.after_fill(at); + if !self.line_at(at.0).is_some_and(|line| line.fills_at(at.1, h.font, h.at, h.opacity, &h.text, h.actual)) { + break; + } + places.push(at); + } + if places.len() == held.len() { + return Some(places); + } + } + None + } + + /// [`Self::settle_strokes`], each stroke matched to the last glyph it may go over (`last`), + /// or, when too many are held ([`Self::hold_stroke`]), as the start of a pass that goes on + /// ([`Self::replayed`]). + fn settle(&mut self, last: bool) { + if self.held.is_empty() { + return; + } + let held = std::mem::take(&mut self.held); + let mut places = vec![]; + if last { + let mut before = None; + for h in held.iter().rev() { + let Some(p) = self.last_fill(before, h) else { break }; + places.push(p); + before = Some(p); + } + places.reverse(); + } else if let Some(p) = self.replayed(&held) { + places = p; + } + // Each held stroke goes over the first glyph it may go over after the one before it + // does ([`Self::hold_stroke`]), so the last ones are found too: this is only a guard. + if places.len() != held.len() { + places = held.iter().map(|h| h.first).collect(); + } + // The slots of the parked lines finished so far, which the later places count in. + let mut finished = 0usize; + for (h, (slot, index)) in held.into_iter().zip(places) { + let slot = slot.saturating_sub(finished); + let parked = self.parked.len(); + // The lines before the one stroked are past the stroke pass: they are finished. + self.release_parked(slot); + finished = finished.saturating_add(slot.min(parked)); + let target = match self.parked.first_mut() { + Some((line, glyphs)) if slot < parked => Some((line, glyphs)), + _ => self.text.as_mut().map(|line| (line, &mut self.text_glyphs)), + }; + if let Some((line, glyphs)) = target + && line.stroke_filled_at(index, h.stroke, h.overprint) + { + // Upright glyphs aren't kept as outlines (nor are those filled only): a vertical + // line that came in as its outlines would lose the ones filled only. + glyphs.extend(h.glyph); + } + } + } + + /// Finish `line` of type, whose `glyphs` are its outlines ([`Self::keep_glyph`]). `true`: + /// it was kept as them ([`Self::end_text`]). + fn end_line(&mut self, mut line: TextLine, glyphs: Vec) -> bool { let held = std::mem::take(&mut line.held); // Type the file names itself (ActualText) is in reading order as it stands. let checked = !glyphs.is_empty() && line.mapped() && !line.has_type3; @@ -880,13 +1178,9 @@ impl<'p> Builder<'p> { scale: f64, overprint: bool, ) { - let Some((paint, stroke)) = drawn else { return }; - let mut path = o.outline(); - if path.elements().is_empty() { - return; + if let Some(g) = glyph_run(o, m, drawn, opacity, scale, overprint) { + self.text_glyphs.push(g); } - path.apply_affine(m); - self.text_glyphs.push(GlyphRun { path, paint, opacity, stroke, scale, overprint }); } fn type3_font_name(&mut self, key: u128) -> FontInfo { @@ -1150,10 +1444,22 @@ impl<'p> Builder<'p> { Some(top) => line.push_upright(&look, at, opacity, Upright { top }, &text), None => line.push(&look, at, opacity, advance, &text), }; + let stroking = look.fill.is_none() && look.stroke.is_some(); + // A stroke over a glyph filled before it, on the open line or one the same operator's + // kerning finished: matched once its stroke pass ends. + if let Some(s) = &look.stroke + && stroking + { + let glyph = if top.is_none() { glyph_run(o, m, drawn.clone(), opacity, scale, overprint) } else { None }; + let h = HeldStroke { font: key, at, opacity, text: text.clone(), stroke: s.clone(), overprint, glyph, actual: false, first: (0, 0) }; + if self.hold_stroke(h) { + return true; + } + } self.flush_glyphs(); // A stroke over the glyph just filled (fill and stroke rendering). if let (Some(s), Some(line)) = (&look.stroke, &mut self.text) - && look.fill.is_none() + && stroking && line.stroke_filled(key, at, opacity, &text, s.clone(), overprint) { // Upright glyphs aren't kept as outlines (nor, below, are those filled only): a @@ -1163,8 +1469,12 @@ impl<'p> Builder<'p> { } return true; } + // Stroked type of its own ends the stroke pass of the glyphs filled before it. + if stroking { + self.end_fills(); + } if !self.text.as_mut().is_some_and(place) { - self.flush_text(); + self.park_text(!stroking); let mut line = TextLine::new(at, opacity); place(&mut line); self.text = Some(line); @@ -1184,6 +1494,25 @@ impl<'p> Builder<'p> { } } +/// Glyph `o` placed by `m` and drawn with `drawn` as the outline it is kept as +/// ([`Builder::keep_glyph`]). Nothing for a glyph that shows nothing. +fn glyph_run( + o: &craft_pdf::interpret::font::OutlineGlyph, + m: Affine, + drawn: Option<(Paint, Option)>, + opacity: f32, + scale: f64, + overprint: bool, +) -> Option { + let (paint, stroke) = drawn?; + let mut path = o.outline(); + if path.elements().is_empty() { + return None; + } + path.apply_affine(m); + Some(GlyphRun { path, paint, opacity, stroke, scale, overprint }) +} + /// The characters of one glyph in the order they are drawn: a PDF names a ligature's characters /// in logical order (lam then alef for لا), while a horizontal line of type is gathered glyph by /// glyph in visual order and only then put back in logical order. Right-to-left characters are diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 452090c6b6..47924a717d 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -453,12 +453,20 @@ impl<'a> Device<'a> for Builder<'_> { self.flush(); } self.marked.pop(); - self.actual.end(); + // A span's glyphs are stroked within it: a stroke after it goes over none of them. + if self.actual.end() { + self.end_fills(); + } } fn actual_text(&mut self, text: &[u8]) { + let active = self.actual.active(); if self.nested == 0 && self.text_as == crate::TextAs::Text && !self.actual.set(text) { self.warn("ActualText beyond the import size or nesting limit was left to glyph mappings"); } + // Nor does a stroke in a span go over a glyph filled before it. + if !active && self.actual.active() { + self.end_fills(); + } } } diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index d8068279cf..26ad4db3ee 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -58,6 +58,24 @@ pub(super) struct GlyphRun { pub(super) overprint: bool, } +/// A stroke over a glyph filled before it (fill and stroke rendering), held with the stroke pass +/// it is part of ([`Builder::hold_stroke`]): the glyph's font, placement, opacity and text, the +/// stroke, whether it overprints, the glyph's outline as drawn (kept as for a line of type kept +/// as outlines; none for a glyph set upright or one of an ActualText span), whether it is one of +/// an ActualText span, and the first glyph filled so it may go over, as its line's place among +/// the parked lines and the open one and its index in the line's filled glyphs. +pub(super) struct HeldStroke { + pub(super) font: u128, + pub(super) at: super::Placement, + pub(super) opacity: f32, + pub(super) text: String, + pub(super) stroke: TypeStroke, + pub(super) overprint: bool, + pub(super) glyph: Option, + pub(super) actual: bool, + pub(super) first: (usize, usize), +} + /// How often a tiling pattern was read, and the art (as its paints) each reading drew with the /// swatch made for it. pub(super) type PatternReadings = (u32, Vec<(Vec, String)>); @@ -94,6 +112,19 @@ pub(super) struct Builder<'p> { /// kept as: what the line becomes when its type wouldn't draw as the file does /// ([`super::reshaped`]). pub(super) text_glyphs: Vec, + /// Lines of type a text-showing operator's fill pass finished (a `TJ`'s kerning starts a new + /// line part way through) that its stroke pass may still go over, oldest first, each with + /// its [`text_glyphs`](Self::text_glyphs): written before the open line, in this order + /// ([`Builder::park_text`]). + pub(super) parked: Vec<(TextLine, Vec)>, + /// The strokes of a text-showing operator's stroke pass over glyphs it filled on the + /// [`parked`](Self::parked) lines and the open one, held until the pass ends to be matched to + /// the glyphs it strokes ([`Builder::settle_strokes`]). + pub(super) held: Vec, + /// The glyphs of the lines a fill pass finished beyond the most kept for their stroke pass that + /// a stroke may still have gone over, until the first stroke after them + /// ([`Builder::hold_stroke`]) or a boundary of stroke passes ([`Builder::end_fills`]). + pub(super) lost: Option, pub(super) text_as: TextAs, pub(super) actual: super::actual_text::ActualText, pub(super) images: HashMap, diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index a6b128e042..9614fa5340 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -233,10 +233,8 @@ pub(crate) struct TextLine { slots: Vec>, /// Per character: authored logical order must survive visual-to-logical reconstruction. authored: Vec, - /// Fill callbacks in an authored span, for the reader's later stroke pass. - actual_fills: HashMap<(u128, u64, u64), Option>, /// The glyphs filled without a stroke, in drawing order, for a stroke drawn over them later - /// ([`stroke_filled`](Self::stroke_filled)). + /// ([`stroke_filled`](Self::stroke_filled)), those of an ActualText span among them. filled: Vec, /// The first of [`filled`](Self::filled) a stroke may still be drawn over: a stroke matches /// glyphs in the order they were filled, and each at most once. @@ -246,6 +244,10 @@ pub(crate) struct TextLine { pending: Option, /// The last glyph's placement. last_at: Placement, + /// The last glyph was drawn before a boundary of stroke passes ([`end_fills`](Self::end_fills)): + /// no stroke drawn since goes over it, not even as the glyph just drawn + /// ([`stroke_last`](Self::stroke_last)). + last_closed: bool, /// The first glyph was set vertically ([`Upright`]). upright: Option, /// The glyphs make a column (vertical type), each below the last. @@ -279,7 +281,9 @@ struct Slot { } /// A glyph filled without a stroke: its font and placement, and where its text is in the line's -/// runs (the run's index, the text's byte offset in it and its length). +/// runs (the run's index, the text's byte offset in it and its length). A glyph of an ActualText +/// span has `actual`: `Some(true)` for the glyph whose run holds the replacement text, +/// `Some(false)` for the glyphs after it, which add no text (`len` 0 for both). #[derive(Clone, Copy, Debug)] struct Filled { font: u128, @@ -287,6 +291,57 @@ struct Filled { run: usize, start: usize, len: usize, + actual: Option, +} + +/// Whether a stroke over glyph `text` drawn at `at` in `font` at `opacity` may be drawn over a +/// glyph `fill` filled (its font, placement, whether it is a glyph of an ActualText span, and its +/// text) on a line that is `opaque` or not ([`TextLine::fills_at`]). +fn may_stroke(fill: (u128, Placement, bool, Option<&str>), opaque: bool, font: u128, at: Placement, opacity: f32, text: &str, actual: bool) -> bool { + let (g_font, g_at, g_actual, g_text) = fill; + if actual { + let same = |a: f64, b: f64| a.to_bits() == b.to_bits(); + return g_actual && g_font == font && same(g_at.origin.x, at.origin.x) && same(g_at.origin.y, at.origin.y); + } + !g_actual && opacity >= 0.999 && opaque && g_font == font && g_at.same_as(&at) && g_text == Some(text) +} + +/// The glyphs a stroke could still go over on lines of type finished before their stroke pass +/// could end: lines beyond the most a fill pass keeps for its stroke pass. The device isn't told +/// where an operator starts, so a stroke pass over such a line can't be told from one over the +/// glyphs kept: its first stroke, over a glyph finished so, may match one of them instead. Kept up +/// to [`MAX_LOST_FILLS`](Self::MAX_LOST_FILLS), beyond which any stroke may be over one. +#[derive(Clone, Debug, Default)] +pub(crate) struct LostFills { + /// Each glyph's font, placement, whether it is a glyph of an ActualText span, its text and + /// whether its line is opaque. + fills: Vec<(u128, Placement, bool, Option, bool)>, + /// More glyphs than [`MAX_LOST_FILLS`](Self::MAX_LOST_FILLS) were finished so. + overflowed: bool, +} + +impl LostFills { + /// The most glyphs kept, for bounded work and memory on hostile input. + pub const MAX_LOST_FILLS: usize = 4096; + + /// Add the glyphs `line` filled that a stroke may still go over. + pub fn add(&mut self, line: &TextLine) { + let opaque = line.opacity >= 0.999; + for g in line.filled.get(line.stroked..).unwrap_or_default() { + if self.fills.len() >= Self::MAX_LOST_FILLS { + self.overflowed = true; + return; + } + self.fills.push((g.font, g.at, g.actual.is_some(), line.glyph_text(g).map(str::to_string), opaque)); + } + } + + /// Whether a stroke over glyph `text` drawn at `at` in `font` at `opacity` may be drawn over + /// one of the glyphs ([`TextLine::fills_at`]). + pub fn may_stroke(&self, font: u128, at: Placement, opacity: f32, text: &str, actual: bool) -> bool { + self.overflowed + || self.fills.iter().any(|(f, a, act, t, opaque)| may_stroke((*f, *a, *act, t.as_deref()), *opaque, font, at, opacity, text, actual)) + } } /// Glyphs next to each other in one run that a stroke is drawn over, not yet restyled @@ -331,11 +386,11 @@ impl TextLine { text_bytes: 0, slots: vec![], authored: vec![], - actual_fills: HashMap::new(), filled: vec![], stroked: 0, pending: None, last_at: at, + last_closed: false, upright: None, column: false, ink: vec![], @@ -382,10 +437,10 @@ impl TextLine { let Some((last, _, run)) = self.runs.last_mut() else { self.runs.push((look.clone(), 0.0, text.to_string())); self.last_start = 0; - self.record_actual_fill(look, at, content); self.record_filled(look, at, content); self.authored.extend(text.chars().map(|_| content.authored())); (self.upright, self.next, self.last, self.last_at) = (Some(upright), at.origin + down * at.size, at.origin, at); + self.last_closed = false; return true; }; let across = (at.origin - self.at.origin).dot(self.at.dir); @@ -420,12 +475,12 @@ impl TextLine { self.runs.push((look.clone(), 0.0, text.to_string())); self.last_start = 0; } - self.record_actual_fill(look, at, content); self.record_filled(look, at, content); self.authored.extend(text.chars().map(|_| content.authored())); self.next = at.origin + down * at.size; self.last = at.origin; self.last_at = at; + self.last_closed = false; true } @@ -522,7 +577,6 @@ impl TextLine { self.runs.push((look.clone(), 0.0, text.to_string())); self.last_start = 0; } - self.record_actual_fill(look, at, content); self.record_filled(look, at, content); self.text_bytes = self.text_bytes.saturating_add(text.len()); if !pen { @@ -539,41 +593,38 @@ impl TextLine { } self.last = at.origin; self.last_at = at; + self.last_closed = false; self.last_dir = at.dir; self.last_size = at.size; self.baseline.push(at.origin); true } - fn record_actual_fill(&mut self, look: &Look, at: Placement, content: TextContent<'_>) { - if content.authored() && look.fill.is_some() { - let run = matches!(content, TextContent::Actual(_)).then(|| self.runs.len().saturating_sub(1)); - self.actual_fills.insert((look.font, at.origin.x.to_bits(), at.origin.y.to_bits()), run); - } - } - /// Note glyph `content` just added to the last run, filled without a stroke, for a stroke - /// drawn over it later. + /// drawn over it later: a glyph of an ActualText span too, whose text is the replacement's + /// (the first glyph's) or none. fn record_filled(&mut self, look: &Look, at: Placement, content: TextContent<'_>) { - let len = content.text().len(); - if content.authored() || len == 0 || look.fill.is_none() || look.stroke.is_some() { + if look.fill.is_none() || look.stroke.is_some() { return; } - let run = self.runs.len().saturating_sub(1); - self.filled.push(Filled { font: look.font, at, run, start: self.last_start, len }); + let (run, start) = (self.runs.len().saturating_sub(1), self.last_start); + let (start, len, actual) = match content { + TextContent::Mapped(text) if !text.is_empty() => (start, text.len(), None), + TextContent::Mapped(_) => return, + TextContent::Actual(_) => (0, 0, Some(true)), + TextContent::Pen => (0, 0, Some(false)), + }; + self.filled.push(Filled { font: look.font, at, run, start, len, actual }); } /// The reader fills a whole Tj/TJ before replaying its glyphs as strokes. A replay /// must neither consume the replacement nor rewind the pen. Only the first glyph's - /// style belongs to the replacement; suppressed glyphs have no text to restyle. + /// style belongs to the replacement; suppressed glyphs have no text to restyle. The stroke + /// goes over the next glyph of the span filled in `font` at `at`, not stroked yet + /// ([`stroke_filled_at`](Self::stroke_filled_at)). pub fn stroke_actual(&mut self, font: u128, at: Placement, stroke: TypeStroke, overprint: bool) -> bool { - self.flush_stroke(); - let key = (font, at.origin.x.to_bits(), at.origin.y.to_bits()); - let Some(run) = self.actual_fills.remove(&key) else { return false }; - if let Some((look, ..)) = run.and_then(|i| self.runs.get_mut(i)) { - (look.stroke, look.overprint_stroke) = (Some(stroke), overprint); - } - true + let Some(index) = self.next_filled(0, font, at, 1.0, "", true) else { return false }; + self.stroke_filled_at(index, stroke, overprint) } /// Has the baseline turned (more than about 3° from the first glyph to the last)? @@ -625,21 +676,35 @@ impl TextLine { // A stroke at another opacity than the fill's (`CA` and `ca` differ), or over a // translucent fill, is type of its own. let opaque = opacity >= 0.999 && self.opacity >= 0.999; - let rest = if opaque { self.filled.get(self.stroked..) } else { None }; - let found = rest.and_then(|rest| { - rest.iter().position(|g| { - g.font == font - && g.at.same_as(&at) - && self.runs.get(g.run).and_then(|(.., t)| t.get(g.start..g.start.saturating_add(g.len))) == Some(text) - }) - }); - let Some(index) = found.map(|i| self.stroked.saturating_add(i)) else { + let Some(index) = self.next_filled(0, font, at, opacity, text, false) else { // Stroked text of its own (stroke rendering): no later stroke goes back over the // glyphs filled before it, so no stroke looks through them again. self.stroked = self.filled.len(); // Nor does a translucent stroke join the glyph just filled. return opaque && self.stroke_last(font, at, text, stroke, overprint); }; + self.stroke_filled_at(index, stroke, overprint) + } + + /// A stroke over the glyph filled at `index` in [`filled`](Self::filled), not stroked yet + /// ([`next_filled`](Self::next_filled), [`last_filled`](Self::last_filled)): that glyph is + /// stroked as [`stroke_filled`](Self::stroke_filled) strokes the glyph it finds, and no later + /// stroke goes over the glyphs filled before it. `false`: there is no such glyph. + /// A glyph of an ActualText span restyles its replacement's run at once, if it holds it. + pub fn stroke_filled_at(&mut self, index: usize, stroke: TypeStroke, overprint: bool) -> bool { + if index < self.stroked || index >= self.filled.len() { + return false; + } + if let Some(g) = self.filled.get(index).copied() + && let Some(owner) = g.actual + { + self.flush_stroke(); + if let Some((look, ..)) = self.runs.get_mut(g.run).filter(|_| owner) { + (look.stroke, look.overprint_stroke) = (Some(stroke), overprint); + } + self.stroked = index.saturating_add(1); + return true; + } let continues = self .pending .as_ref() @@ -661,6 +726,68 @@ impl TextLine { true } + /// The first glyph from index `from` of [`filled`](Self::filled) on, not stroked yet, that a + /// stroke over glyph `text` drawn at `at` in `font` at `opacity` may be drawn over + /// ([`fills_at`](Self::fills_at)). `None` for a translucent fill or stroke. + pub fn next_filled(&self, from: usize, font: u128, at: Placement, opacity: f32, text: &str, actual: bool) -> Option { + let from = from.max(self.stroked); + let i = self.filled.get(from..)?.iter().position(|g| self.fills(g, font, at, opacity, text, actual))?; + Some(from.saturating_add(i)) + } + + /// The last glyph before index `before` of [`filled`](Self::filled), not stroked yet, that a + /// stroke over glyph `text` drawn at `at` in `font` at `opacity` may be drawn over + /// ([`fills_at`](Self::fills_at)). + pub fn last_filled(&self, before: usize, font: u128, at: Placement, opacity: f32, text: &str, actual: bool) -> Option { + let rest = self.filled.get(self.stroked..before.min(self.filled.len()))?; + let i = rest.iter().rposition(|g| self.fills(g, font, at, opacity, text, actual))?; + Some(self.stroked.saturating_add(i)) + } + + /// Whether the glyph filled at `index` in [`filled`](Self::filled), not stroked yet, is one a + /// stroke over glyph `text` drawn at `at` in `font` at `opacity` may be drawn over: opaque, + /// in the same font, with the same placement and text. With `actual`, a stroke over a glyph + /// of an ActualText span instead: a glyph of the span filled in the same font at the same + /// origin, at any opacity ([`stroke_actual`](Self::stroke_actual)): the span's replacement + /// text goes with the glyph filled first, so a translucent stroke kept apart from its fill + /// would be type with no text, and come in as nothing. + pub fn fills_at(&self, index: usize, font: u128, at: Placement, opacity: f32, text: &str, actual: bool) -> bool { + index >= self.stroked && self.filled.get(index).is_some_and(|g| self.fills(g, font, at, opacity, text, actual)) + } + + /// How many glyphs the line filled for a stroke drawn over them later, stroked or not + /// ([`filled`](Self::filled)). + pub fn filled_len(&self) -> usize { + self.filled.len() + } + + /// [`fills_at`](Self::fills_at) for glyph `g`. + fn fills(&self, g: &Filled, font: u128, at: Placement, opacity: f32, text: &str, actual: bool) -> bool { + let (fill, opaque) = ((g.font, g.at, g.actual.is_some(), self.glyph_text(g)), self.opacity >= 0.999); + may_stroke(fill, opaque, font, at, opacity, text, actual) + } + + /// The text of filled glyph `g` in the line's runs. + fn glyph_text(&self, g: &Filled) -> Option<&str> { + self.runs.get(g.run).and_then(|(.., t)| t.get(g.start..g.start.saturating_add(g.len))) + } + + /// Whether a stroke drawn later may still be drawn over a glyph of the line (fill and stroke + /// rendering): an opaque glyph filled and not stroked yet, or a filled glyph of an + /// ActualText span ([`stroke_actual`](Self::stroke_actual)). + pub fn awaits_stroke(&self) -> bool { + self.filled.get(self.stroked..).is_some_and(|rest| rest.iter().any(|g| g.actual.is_some() || self.opacity >= 0.999)) + } + + /// No stroke drawn from now on goes over a glyph the line filled so far: a stroke pass does + /// not go back past a stroke of its own (one over no glyph filled) or the start or end of an + /// ActualText span ([`stroke_filled`](Self::stroke_filled)). Nor does one restyle the glyph + /// drawn last ([`stroke_last`](Self::stroke_last)). + pub fn end_fills(&mut self) { + self.stroked = self.filled.len(); + self.last_closed = true; + } + /// Restyle the glyphs gathered for a stroke ([`stroke_filled`](Self::stroke_filled)): their /// text becomes a run of its own with the stroke, unless the run is stroked so already, and the /// text before and after it in the run keeps its stroke. Text that comes right after a run @@ -729,9 +856,6 @@ impl TextLine { for g in self.filled.iter_mut().skip(from) { (g.run, g.start) = moved(g.run, g.start); } - for i in self.actual_fills.values_mut().flatten() { - *i = moved(*i, 0).0; - } if last { self.last_start = moved(run, self.last_start).1; } @@ -744,7 +868,14 @@ impl TextLine { /// ([`Look::takes`]): then the glyph's text becomes a run of its own with this stroke, and /// the glyphs before it stay unstroked (#7741). The line's text is the same either way, so /// the characters' slots, gaps and authored flags, kept along the whole line, still line up. + /// + /// Not a glyph drawn before a boundary of stroke passes ([`end_fills`](Self::end_fills)): + /// a stroke after the end of an ActualText span would otherwise stroke the span's replacement + /// text, and one after its start a glyph filled before the span (#8543). fn stroke_last(&mut self, font: u128, at: Placement, glyph: &str, stroke: TypeStroke, overprint: bool) -> bool { + if self.last_closed { + return false; + } self.flush_stroke(); let start = self.last_start; let last_at = self.last_at; diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 5b33683dcf..dada741c9d 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; -use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; +use vectorcraft_color::{BlendMode, Color, GradientKind, GradientStop, Paint}; use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors}; use vectorcraft_doc::overprint::{darken_overprints, is_black_ink, is_white}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind}; @@ -175,33 +175,74 @@ impl<'a> Separator<'a> { /// carry counts as none. A link to a swatch the document lacks separates as the color's own /// values, so such a black counts as unlinked. fn no_ink(&self, plate: &str, p: &Paint) -> bool { - let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot)); - let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false)); match p { Paint::Solid { color, swatch, tint } => { - none(color, process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint)))) + self.none(color, self.process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint)))) } Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) { - Some(f) => f.points.iter().all(|pt| none(&pt.color, true, self.ink(plate, &pt.color, None))), - None => { - !g.gradient.stops.is_empty() - && g.gradient.stops.iter().all(|s| { - let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates); - none(&s.color, s.plates.is_none() && process(s.swatch.as_deref()), ink) - }) - } + Some(f) => f.points.iter().all(|pt| self.point_none(plate, &pt.color)), + None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| self.stop_none(plate, s)), }, _ => false, } } + /// Whether a color linked to swatch `swatch` separates as process inks: no link, or a link + /// to a process swatch or to one the document lacks, other than Registration. + fn process(&self, swatch: Option<&str>) -> bool { + swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot)) + } + + /// Whether `ink` of color `c` (separating as process inks when `process` is true) counts as + /// none, as [`Self::no_ink`] says. + fn none(&self, c: &Color, process: bool, ink: f32) -> bool { + ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false)) + } + + /// Whether gradient stop `s` puts none of ink `plate` down, as [`Self::no_ink`] says. + fn stop_none(&self, plate: &str, s: &GradientStop) -> bool { + let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates); + self.none(&s.color, s.plates.is_none() && self.process(s.swatch.as_deref()), ink) + } + + /// Whether a freeform gradient's point of color `c` puts none of ink `plate` down, as + /// [`Self::no_ink`] says. + fn point_none(&self, plate: &str, c: &Color) -> bool { + self.none(c, true, self.ink(plate, c, None)) + } + + /// On a PostScript plate, make paper white the stops and points of overprinting gradient `p` + /// that put none of ink `plate` down while others do ([`Self::no_ink`]'s rule for each): the + /// writer leaves the plate below as it is where the gradient is paper white. + fn clear_inkless_stops(&self, plate: &str, p: &mut Paint) { + let Paint::Gradient(g) = p else { return }; + if !self.postscript { + return; + } + let paper = Color::Gray { k: 0.0 }; + match g.freeform.as_mut().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) { + Some(f) => { + for pt in f.points.iter_mut().filter(|pt| self.point_none(plate, &pt.color)) { + pt.color = paper; + } + } + None => { + for s in g.gradient.stops.iter_mut().filter(|s| self.stop_none(plate, s)) { + *s = GradientStop { color: paper, swatch: None, tint: 1.0, plates: None, ..s.clone() }; + } + } + } + } + /// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and /// overprinting character fills and strokes, that put none of ink `plate` down leave its plate /// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which /// knock out). A writer without blending modes (PostScript) then keeps the ink below them, /// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on /// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting - /// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). + /// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). On a + /// PostScript plate, the stops and points of such a gradient that put none of the ink down + /// become paper white ([`Self::clear_inkless_stops`]), which the writer leaves out there. fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc, discard_white: bool) { let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p); let n = Arc::make_mut(a); @@ -212,15 +253,21 @@ impl<'a> Separator<'a> { }; if normal && inkless(it.overprint(), it.paint()) { *it.paint_mut() = Paint::None; + } else if normal && it.overprint() { + self.clear_inkless_stops(plate, it.paint_mut()); } } if let NodeKind::Text(t) = &mut n.kind { for r in &mut t.runs { if inkless(r.style.overprint_fill, &r.style.fill) { r.style.fill = Paint::None; + } else if r.style.overprint_fill { + self.clear_inkless_stops(plate, &mut r.style.fill); } if inkless(r.style.overprint_stroke, &r.style.stroke) { r.style.stroke = Paint::None; + } else if r.style.overprint_stroke { + self.clear_inkless_stops(plate, &mut r.style.stroke); } } } diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 588273faf9..bee9e61bad 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -999,6 +999,42 @@ fn overprinting_paints_keep_their_faint_ink_on_postscript_plates() { } } +#[test] +fn a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates() { + // 0.4% cyan beside 100% K counts as black on a PostScript plate stop by stop, as a solid fill + // of it does: the cyan plate draws that stop of an overprinting gradient as paper white. A + // PDF plate and a gradient that does not overprint keep the 0.4%. + let stops = vec![GradientStop::new(0.0, Color::cmyk(0.004, 0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::cmyk(0.5, 0.0, 0.0, 0.0))]; + let fade = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let square = |x: f64, overprint: bool| { + let r = shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)); + let mut n = Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(fade.clone(), Paint::None, 0.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = overprint; + } + n + }; + let d = over_cyan(vec![square(10.0, true), square(40.0, false)]); + // The cyan plate's stops of each gradient, in thousandths of the ink. + let stops = |postscript: bool| { + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let mut all = vec![]; + p.plates[0].walk(|n| { + if let Some(Paint::Gradient(g)) = n.appearance.fill().map(|f| &f.paint) { + let gray = |s: &GradientStop| match s.color { + Color::Gray { k } if s.swatch.is_none() => (k * 1000.0).round(), + c => panic!("{c:?}"), + }; + all.push(g.gradient.stops.iter().map(gray).collect::>()); + } + }); + all + }; + assert_eq!(stops(true), [[0.0, 500.0], [4.0, 500.0]], "PostScript: the overprinting gradient, the other"); + assert_eq!(stops(false), [[4.0, 500.0], [4.0, 500.0]], "PDF"); +} + #[test] fn overprinting_type_leaves_the_inks_below_on_separations() { let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), ..Default::default() }; diff --git a/crates/pdf/src/tests/textstroke.rs b/crates/pdf/src/tests/textstroke.rs index 1cc1edf5ba..e051b8bd6b 100644 --- a/crates/pdf/src/tests/textstroke.rs +++ b/crates/pdf/src/tests/textstroke.rs @@ -346,3 +346,225 @@ fn glyphs_filled_and_stroked_one_by_one_stay_one_run() { assert_eq!(type_runs(content), [vec![("ABC".to_string(), true, true)]], "{content}"); } } + +/// Fill and stroke rendering of a `TJ` whose kerning starts a new line part way through: the +/// reader fills every glyph of the operator before it strokes them, and each part comes in as +/// type filled and stroked, in the order drawn, not as each part filled and then each part +/// stroked over it (#8543). So too a `TJ` that jumps back to start a line before it and one whose +/// kerning starts two new lines. In a span with replacement text (`ActualText`) it stays one type +/// object, on the first glyph's line and in its style, filled and stroked; small kerning keeps +/// one line as before. +#[test] +fn a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked() { + // Each type object as its text, and whether all of it is filled and all of it stroked. + let objects = |content: &str| -> Vec<(String, bool, bool)> { + type_runs(content) + .into_iter() + .map(|runs| (runs.iter().map(|r| r.0.as_str()).collect(), runs.iter().all(|r| r.1), runs.iter().all(|r| r.2))) + .collect() + }; + let both = |text: &str| (text.to_string(), true, true); + for mode in ["2", "6"] { + let cases = [ + ("/F1 48 Tf 20 80 Td [(AB) -3500 (CD)] TJ", vec![both("AB"), both("CD")]), + ("/F1 24 Tf 20 80 Td [(AB) -3500 (CD) -3500 (EF)] TJ", vec![both("AB"), both("CD"), both("EF")]), + ("/F1 24 Tf 200 80 Td [(AB) 6000 (CD)] TJ", vec![both("AB"), both("CD")]), + ("/F1 48 Tf 20 80 Td [(AB) -100 (CD)] TJ", vec![both("ABCD")]), + // In a span with replacement text, which places all of its text with the first glyph. + ("/F1 48 Tf 20 80 Td /Span << /ActualText (ABCD) >> BDC [(AB) -3500 (CD)] TJ EMC", vec![both("ABCD")]), + ]; + for (show, want) in cases { + let content = format!("BT {mode} Tr {show} 0 Tr ET"); + assert_eq!(objects(&content), want, "{content}: {:?}", type_runs(&content)); + } + } +} + +/// Stroke rendering (modes 1 and 5) of a `TJ` whose kerning starts a new line stays stroke only, +/// one type object per line (#8543). +#[test] +fn a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only() { + for mode in ["1", "5"] { + let content = format!("BT {mode} Tr /F1 48 Tf 20 80 Td [(AB) -3500 (CD)] TJ 0 Tr ET"); + let want = [vec![("AB".to_string(), false, true)], vec![("CD".to_string(), false, true)]]; + assert_eq!(type_runs(&content), want, "{content}"); + } +} + +/// Translucent type filled and stroked by a `TJ` whose kerning starts a new line stays a filled +/// object and a stroked one for each part, in the order the file draws them (#8015, #8543). +#[test] +fn a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> /ExtGState << /G << /ca 0.5 /CA 0.5 >> >>"; + let content = "/G gs 0 0 0 RG 1 1 0.8 rg 3 w BT 2 Tr /F1 48 Tf 20 80 Td [(AB) -3500 (CD)] TJ 0 Tr ET"; + let bytes = pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, content) }], None); + let d = import(&bytes).unwrap(); + let mut types = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let st = t.first_style(); + types.push((t.plain_text(), n.opacity < 1.0, !st.fill.is_none(), !st.stroke.is_none())); + } + }); + let part = |text: &str, fill: bool| (text.to_string(), true, fill, !fill); + assert_eq!(types, [part("AB", true), part("CD", true), part("AB", false), part("CD", false)], "{content}"); +} + +/// Fill and stroke rendering of a `TJ` whose kerning goes back to draw a glyph again where it +/// drew one before, on a line of its own: the reader strokes the glyphs in the order it filled +/// them, so each copy is filled and stroked, whether the copy drawn last ends the operator (the +/// open line) or a line after it does (a finished one), and however often it comes back +/// (#8543). A glyph filled and stroked by an operator of its own where one filled before stands +/// still strokes only the one filled last (#8015). +#[test] +fn a_tj_that_draws_a_glyph_again_where_it_drew_one_strokes_each_copy() { + let both = |text: &str| vec![(text.to_string(), true, true)]; + // Helvetica at 48 points: A and B are 667 units wide, so 4834 back after B (3500 on from A) + // draws A again where the first A stands. + for mode in ["2", "6"] { + let cases = [ + ("[(A) -3500 (B) 4834 (A)] TJ", vec![both("A"), both("B"), both("A")]), + ("[(A) -3500 (B) 4834 (A) -6000 (C)] TJ", vec![both("A"), both("B"), both("A"), both("C")]), + ("[(A) -3500 (B) 4834 (A) -3500 (B)] TJ", vec![both("A"), both("B"), both("A"), both("B")]), + ("[(A) -3500 (B) 4834 (A) -3500 (B) 4834 (A)] TJ", vec![both("A"), both("B"), both("A"), both("B"), both("A")]), + ]; + for (show, want) in cases { + let content = format!("BT {mode} Tr /F1 48 Tf 20 80 Td {show} 0 Tr ET"); + assert_eq!(type_runs(&content), want, "{content}"); + } + } + let content = "BT 0 Tr /F1 48 Tf 20 80 Td [(A) -3500 (B) 4834] TJ 2 Tr (A) Tj 0 Tr ET"; + let want = [vec![("A".to_string(), true, false)], vec![("B".to_string(), true, false)], both("A")]; + assert_eq!(type_runs(content), want, "{content}"); +} + +/// A stroke pass longer than the importer holds at once ([`MAX_HELD`] strokes) is matched to its +/// own operator's glyphs, in the order filled: an `A` filled by an operator of its own, then `A` +/// and 4,096 `B`s filled and stroked from the same place, strokes the second `A`, not the first +/// (#8543). +#[test] +fn a_long_stroke_pass_strokes_its_own_glyphs_not_one_filled_before() { + let bs = "B".repeat(4096); + let content = format!("BT /F1 2 Tf 1 0 0 1 20 80 Tm 0 Tr (A) Tj 1 0 0 1 20 80 Tm 2 Tr (A{bs}) Tj 0 Tr ET"); + let looks: Vec> = type_runs(&content); + let want = [vec![("A".to_string(), true, false)], vec![(format!("A{bs}"), true, true)]]; + assert!(looks == want, "{:?}", looks.iter().map(|t| t.iter().map(|r| (r.0.len(), r.1, r.2)).collect::>()).collect::>()); +} + +/// Stroked type of its own (a stroke over no glyph filled) ends the stroke pass of the glyphs +/// filled before it: an `A` filled, a `B` filled on a line of its own, a `C` stroked after the +/// `B`, then a stroke over the `A` is type of its own, drawn last, not a stroke joined to the +/// `A` drawn under the `B` and `C` (#8543). +#[test] +fn a_stroke_after_stroked_type_of_its_own_does_not_join_a_glyph_filled_before() { + let content = "BT /F1 48 Tf 1 0 0 1 20 80 Tm 0 Tr (A) Tj 1 0 0 1 20 140 Tm (B) Tj 1 Tr (C) Tj 1 0 0 1 20 80 Tm (A) Tj 0 Tr ET"; + let run = |text: &str, fill: bool, stroke: bool| (text.to_string(), fill, stroke); + let want = [vec![run("A", true, false)], vec![run("B", true, false), run("C", false, true)], vec![run("A", false, true)]]; + assert_eq!(type_runs(content), want, "{content}"); +} + +/// A stroke in an ActualText span goes over a glyph that span filled, not one an earlier span +/// filled at the same place: each span's replacement text comes in (#8543). +#[test] +fn a_stroke_in_an_actual_text_span_does_not_take_an_earlier_spans_glyph() { + let content = "BT /F1 48 Tf 0 Tr /Span << /ActualText (First) >> BDC 1 0 0 1 20 80 Tm (A) Tj EMC 1 0 0 1 20 140 Tm (B) Tj \ + /Span << /ActualText (Second) >> BDC 1 Tr 1 0 0 1 20 80 Tm (A) Tj EMC 0 Tr ET"; + let run = |text: &str, fill: bool, stroke: bool| vec![(text.to_string(), fill, stroke)]; + assert_eq!(type_runs(content), [run("First", true, false), run("B", true, false), run("Second", false, true)], "{content}"); +} + +/// Fill and stroke rendering of a `TJ` that draws a glyph again where it drew one, in an +/// ActualText span: the strokes go over the glyphs in the order filled, so the replacement text, +/// on the first glyph's line and in its style, is filled and stroked, not left to the copy drawn +/// last, which shows no text (#8543). +#[test] +fn a_tj_that_draws_a_glyph_again_in_an_actual_text_span_strokes_the_replacement() { + for mode in ["2", "6"] { + for show in ["[(A) 667 (A)] TJ", "[(A) -500 (B) 1834 (A)] TJ", "[(A) -3500 (B) 4834 (A)] TJ"] { + let content = format!("BT {mode} Tr /F1 48 Tf 20 80 Td /Span << /ActualText (ABA) >> BDC {show} EMC 0 Tr ET"); + assert_eq!(type_runs(&content), [vec![("ABA".to_string(), true, true)]], "{content}"); + } + } +} + +/// The lines of type one operator's fill pass finishes are kept for its stroke pass up to 64 at +/// a time: a `TJ` whose kerning starts 65 lines comes in as 65 type objects filled and stroked, +/// and one that starts 66 as a filled object and a stroked one for each part, the fills first, +/// as the file draws them (#8543). +#[test] +fn a_tj_over_more_lines_than_are_kept_comes_in_as_fill_and_stroke_apart() { + let content = |n: usize| format!("BT 2 Tr /F1 4 Tf 20 80 Td [{}] TJ 0 Tr ET", vec!["(A)"; n].join(" -3500 ")); + let both = vec![("A".to_string(), true, true)]; + assert_eq!(type_runs(&content(65)), vec![both; 65]); + let (fill, stroke) = (vec![("A".to_string(), true, false)], vec![("A".to_string(), false, true)]); + let want: Vec<_> = std::iter::repeat_n(fill, 66).chain(std::iter::repeat_n(stroke, 66)).collect(); + assert_eq!(type_runs(&content(66)), want); +} + +/// A `TJ` over more lines than are kept whose last part draws its first glyph again at the first +/// glyph's origin still comes in as a filled object and a stroked one for each part: the stroke +/// over the first glyph, whose line was finished, doesn't take the last part's fill (#8543). +#[test] +fn a_tj_over_more_lines_than_are_kept_that_ends_where_it_began_stays_fill_and_stroke_apart() { + // Helvetica's A is 667 units wide: 65 As and 64 kerns of 3,500 back to the first A's origin. + let parts = vec!["(A)"; 65].join(" -3500 "); + let content = format!("BT 2 Tr /F1 4 Tf 20 80 Td [{parts} 267355 (A)] TJ 0 Tr ET"); + let (fill, stroke) = (vec![("A".to_string(), true, false)], vec![("A".to_string(), false, true)]); + let want: Vec<_> = std::iter::repeat_n(fill, 66).chain(std::iter::repeat_n(stroke, 66)).collect(); + assert_eq!(type_runs(&content), want); +} + +/// Type filled and stroked right after a `TJ` over more lines than are kept is filled and +/// stroked as before, whether the `TJ` was filled and stroked or filled only (#8543). +#[test] +fn type_after_a_tj_over_more_lines_than_are_kept_is_filled_and_stroked() { + let parts = vec!["(A)"; 66].join(" -3500 "); + for mode in ["2", "0"] { + let content = format!("BT /F1 4 Tf 20 80 Td {mode} Tr [{parts}] TJ 2 Tr /F1 48 Tf 1 0 0 1 40 150 Tm (B) Tj 0 Tr ET"); + let types = type_runs(&content); + assert_eq!(types.len(), if mode == "2" { 133 } else { 67 }, "{content}"); + assert_eq!(types.last(), Some(&vec![("B".to_string(), true, true)]), "{content}"); + } +} + +/// The start and end of an ActualText span end the stroke pass of the glyphs filled before them, +/// for the stroke over the glyph filled last too: a stroke after the span over the glyph its +/// replacement text came with, or over a glyph filled before an empty span, is type of its own, +/// and the glyph keeps its fill only (#8543). +#[test] +fn a_stroke_after_an_actual_text_span_does_not_take_a_glyph_filled_before_it() { + let run = |text: &str, fill: bool, stroke: bool| vec![(text.to_string(), fill, stroke)]; + let cases = [ + "/Span << /ActualText (A) >> BDC 1 0 0 1 20 80 Tm (A) Tj EMC 1 Tr 1 0 0 1 20 80 Tm (A) Tj", + "1 0 0 1 20 80 Tm (A) Tj /Span << /ActualText (B) >> BDC EMC 1 Tr 1 0 0 1 20 80 Tm (A) Tj", + ]; + for show in cases { + let content = format!("BT /F1 48 Tf 0 Tr {show} 0 Tr ET"); + assert_eq!(type_runs(&content), [run("A", true, false), run("A", false, true)], "{content}"); + } +} + +/// A glyph stroked twice where it was drawn, by stroke rendering or by fill and stroke rendering +/// then stroke rendering, is one type object, as before: a stroke over the glyph drawn last +/// restyles it when nothing ended its stroke pass (#7741, #8015). +#[test] +fn a_glyph_stroked_again_where_it_was_drawn_stays_one_type_object() { + for (show, fill) in [("1 Tr (A) Tj", false), ("2 Tr (A) Tj", true)] { + let content = format!("BT /F1 48 Tf {show} 1 Tr 1 0 0 1 20 80 Tm (A) Tj 0 Tr ET").replace("Tf ", "Tf 1 0 0 1 20 80 Tm "); + assert_eq!(type_runs(&content), [vec![("A".to_string(), fill, true)]], "{content}"); + } +} + +/// A stroke pass longer than the importer holds at once ([`MAX_HELD`] strokes) goes over its own +/// operator's glyphs, filled right before it, also when an operator before it filled the same +/// glyphs at the same places: `A` and 4,095 `B`s filled, then `A` and 4,096 `B`s filled and +/// stroked from the same place strokes the second operator's glyphs, not the first one's (#8543). +#[test] +fn a_long_stroke_pass_does_not_take_the_same_glyphs_filled_by_an_operator_before() { + let (before, now) = ("B".repeat(4095), "B".repeat(4096)); + let content = format!("BT /F1 2 Tf 1 0 0 1 20 80 Tm 0 Tr (A{before}) Tj 1 0 0 1 20 80 Tm 2 Tr (A{now}) Tj 0 Tr ET"); + let looks: Vec> = type_runs(&content); + let want = [vec![(format!("A{before}"), true, false)], vec![(format!("A{now}"), true, true)]]; + assert!(looks == want, "{:?}", looks.iter().map(|t| t.iter().map(|r| (r.0.len(), r.1, r.2)).collect::>()).collect::>()); +} diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index a0748f9b1f..a34896b397 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -64,10 +64,13 @@ use crate::{Frame, Renderer, blend_mode, fill_rule, paint}; mod bounds; mod entries; mod pixels; +mod placement; mod predicates; mod raster; mod renderer; +pub use placement::pinned_appearance_for_geometry_edit; + #[cfg(test)] pub(crate) use bounds::visual_bounds; pub(crate) use bounds::{ diff --git a/crates/render/src/fx/placement.rs b/crates/render/src/fx/placement.rs new file mode 100644 index 0000000000..b5dc86a443 --- /dev/null +++ b/crates/render/src/fx/placement.rs @@ -0,0 +1,94 @@ +//! Stored gradient fits for geometry edits on the renderer's ordinary shape/container paths. + +use vectorcraft_color::Paint; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeKind}; +use vectorcraft_effects::{self as effects, GeomContext}; +use vectorcraft_geom::{BezPath, Rect, Shape}; + +use super::bounds::{apply_carrying, effected_path_carrying, item_effects, node_bezpath}; +use super::predicates::has_non_container_art_fx; +use super::renderer::carried; + +/// Store the current renderer fit of gradients that can be represented by the existing appearance. +/// +/// Alternate materialized art, visible plug-ins, Rasterize and path-coordinate stroke gradients +/// keep their existing fit behavior. An unsupported or non-roundtripping carry also leaves its row +/// unchanged; this neither flattens art nor changes persisted effects. `None` makes no change. +pub fn pinned_appearance_for_geometry_edit(doc: &Document, n: &Node) -> Option { + if !n.appearance.has_unplaced_gradient() || unsupported(n) || has_non_container_art_fx(n) { + return None; + } + // Enclosing geometry effects change the fit outside this node-local pass. + // Without that context, leave the paint fitted rather than storing a false frame. + if doc.ancestry(n.id)?.into_iter().filter(|&id| id != n.id).any(|id| { + doc.node(id).is_some_and(|ancestor| { + matches!(ancestor.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && effects::has_geometry(&ancestor.appearance.effects) + }) + }) { + return None; + } + match &n.kind { + NodeKind::Group { .. } | NodeKind::Layer { .. } => effects::pinned_container_appearance(doc, n), + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => pinned_shape(doc, n), + _ => None, + } +} + +fn rasterizes(fx: &[Effect]) -> bool { + fx.iter().any(|effect| effect.visible && effect.id == effects::RASTERIZE) +} + +fn unsupported(n: &Node) -> bool { + effects::has_plugin_effect(n) + || rasterizes(&n.appearance.effects) + || n.appearance.items.iter().any(|item| { + item.visible() && (rasterizes(item.effects()) || matches!(item, AppearanceItem::Stroke(stroke) if stroke.path_gradient().is_some())) + }) +} + +fn unplaced(item: &AppearanceItem) -> bool { + item.visible() && matches!(item.paint(), Paint::Gradient(gradient) if !gradient.is_placed()) +} + +fn pinned_shape(doc: &Document, n: &Node) -> Option { + let bp = node_bezpath(n)?; + let (geometry, object_carry) = effected_path_carrying(doc, n, &bp); + if geometry.elements().is_empty() { + return None; + } + // Share the renderer's actual temporary object carry and skipped-effect flags. + let temporary = carried(n, &object_carry); + let paints = temporary.as_deref().unwrap_or(n); + let context = GeomContext { doc: Some(doc), ..GeomContext::of(paints) }; + let mut appearance = (*n.appearance).clone(); + let mut changed = false; + for (index, original) in n.appearance.items.iter().enumerate().filter(|(_, item)| unplaced(item)) { + // `item` must belong to the same temporary appearance borrowed by `context.item`: + // that lookup uses pointer identity to recover the actual row index/seed. + let item = paints.appearance.items.get(index)?; + let (item_geometry, item_carry) = apply_carrying(item_effects(item), &geometry, &context.item(item)); + let bounds = item_bounds(item, &geometry, &item_geometry, &item_carry)?; + if let Some(pinned) = effects::pinned_gradient_item(original, bounds, &[&object_carry, &item_carry]) { + *appearance.items.get_mut(index)? = pinned; + changed = true; + } + } + changed.then_some(appearance) +} + +/// The same temporary item carry/skipped flags and `ib` choice as `Renderer::paint_items`. +fn item_bounds(item: &AppearanceItem, geometry: &BezPath, item_geometry: &BezPath, carry: &effects::Carry) -> Option { + let mut appearance = Appearance { items: vec![item.clone()], ..Default::default() }; + if !carry.is_empty() && matches!(item.paint(), Paint::Gradient(_)) { + carry.apply(&mut appearance); + } + let mut item = appearance.items.pop()?; + if carry.skipped() { + carry.hide_skipped(item.effects_mut()); + } + Some(if effects::has_geometry(item_effects(&item)) && !item_geometry.elements().is_empty() { + item_geometry.bounding_box() + } else { + geometry.bounding_box() + }) +} diff --git a/crates/render/src/fx/predicates.rs b/crates/render/src/fx/predicates.rs index e4e479b2e5..08bfceb7f2 100644 --- a/crates/render/src/fx/predicates.rs +++ b/crates/render/src/fx/predicates.rs @@ -25,11 +25,20 @@ pub(crate) fn has_fx(n: &Node) -> bool { /// effect copies it with a gradient or changes its fills and strokes ([`effects::has_transform_art`]), /// or is it a group or layer with an appearance of its own (see [`Renderer::draw_object_fx`])? pub(crate) fn has_object_fx(n: &Node) -> bool { + object_fx(n, true) +} + +/// The alternate-art dispatches other than a group or layer's own container appearance. +pub(super) fn has_non_container_art_fx(n: &Node) -> bool { + object_fx(n, false) +} + +fn object_fx(n: &Node, containers: bool) -> bool { (effects::needs_outline(n) && (visible(&n.appearance.effects) || n.projection().is_some())) || effects::has_item_geometry(n) || effects::has_instance_row_raster(n) || effects::has_transform_art(n) - || effects::has_container_appearance(n) + || (containers && effects::has_container_appearance(n)) || effects::has_crop_marks(n) || effects::addons::halftone::has_halftone(n) || effects::has_adjustment(n) diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 555a121309..d0ad5d65e9 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -1029,7 +1029,7 @@ impl Renderer { /// the Transform effects the geometry pass left out hidden ([`effects::Carry::hide_skipped`]), so /// its raster effects and those of its fills and strokes stay with its art; `None` when it stays /// as it is. -fn carried(n: &Node, carry: &effects::Carry) -> Option> { +pub(super) fn carried(n: &Node, carry: &effects::Carry) -> Option> { let moves = carry.moves(&n.appearance); (moves || carry.skipped()).then(|| { let mut m = n.clone(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index af3a0d4da8..f5437bd65b 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -43,6 +43,7 @@ use lru::FrameCache; pub use brush_fx::instance_art; pub use changed::{Changed, changed, placed_area, view_pixels}; pub use effects::stroke::width_outline; +pub use fx::pinned_appearance_for_geometry_edit; pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, installed_memory, newly_undecodable, set_image_cache_budget}; pub use live::expand_live; pub use pattern::render_pattern_swatch; diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index f814ea65a9..55a14740b1 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -29,7 +29,7 @@ use craft_svg::tree::usvg; use std::borrow::Cow; -use std::cell::RefCell; +use std::cell::{OnceCell, RefCell}; use std::collections::HashMap; use std::fmt::Write as _; use std::ops::{Range, RangeInclusive}; @@ -774,6 +774,10 @@ struct Ctx { /// no usable one. The styles of a `` instance share it, so each path is found and parsed /// once however many `` elements show its text. paths: Rc>>>>, + /// Each element id in the document and the first element in document order that carries it + /// ([`Self::element`]). It is built when the first `` names an element, and the + /// styles of a `` instance share it. + ids: Rc, roxmltree::NodeId>>>, } /// The path a `` follows ([`Ctx::text_path`]). @@ -788,6 +792,11 @@ struct FollowedPath { thread_local! { /// How many times [`Ctx::read_text_path`] has read a ``'s path on this thread. static TEXT_PATH_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times [`Ctx::element`] has walked a document's elements on this thread. + static ID_WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// When set, [`Ctx::element`] walks the document for each id instead of using the map, so + /// tests can compare the two. + static LINEAR_IDS: std::cell::Cell = const { std::cell::Cell::new(false) }; } impl Ctx { @@ -802,6 +811,7 @@ impl Ctx { elems: RefCell::default(), strong: RefCell::default(), paths: Rc::default(), + ids: Rc::default(), }; let root = xml.root_element(); let dim = |a: &str| root.attribute(a).and_then(|v| cx.length(v, DEFAULT_FONT_SIZE, 0.0)).filter(|v| *v > 0.0); @@ -824,6 +834,7 @@ impl Ctx { elems: RefCell::default(), strong: RefCell::default(), paths: self.paths.clone(), + ids: self.ids.clone(), } } @@ -1219,7 +1230,7 @@ impl Ctx { Some(d) => BezPath::from_svg(d).ok()?, None => { let id = href(tp)?.trim().strip_prefix('#')?; - let el = xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id))?; + let el = self.element(xml, id)?; let d = match el.tag_name().name() { "path" => el.attribute("d")?.to_string(), _ => self.shape_path(el)?, @@ -1238,6 +1249,32 @@ impl Ctx { usable.then_some(FollowedPath { path: bp, author_length }) } + /// The first element in document order whose `id` is `id`, as the DOM's `getElementById` + /// finds it (https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid). The first + /// call walks `xml` once to build [`Self::ids`]; later calls look the id up there. `xml` is + /// the document [`Self::new`] read. + fn element<'a, 'i>(&self, xml: &'a roxmltree::Document<'i>, id: &str) -> Option> { + #[cfg(test)] + if LINEAR_IDS.get() { + ID_WALKS.set(ID_WALKS.get() + 1); + return xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id)); + } + let ids = self.ids.get_or_init(|| { + #[cfg(test)] + ID_WALKS.set(ID_WALKS.get() + 1); + let mut ids = HashMap::new(); + for n in xml.descendants().filter(|n| n.is_element()) { + if let Some(id) = n.attribute("id") { + ids.entry(Box::from(id)).or_insert(n.id()); + } + } + ids + }); + let el = xml.get_node(*ids.get(id)?)?; + debug_assert_eq!(el.attribute("id"), Some(id), "the id map was built from another document"); + Some(el) + } + /// The equivalent path of a basic shape (SVG 2 › Basic Shapes), as path data: what a /// `` that points at it follows. Circles and ellipses start at 3 o'clock and rounded /// rects at the end of the top-left corner, all running clockwise; lines and polylines follow diff --git a/crates/svg/src/import/text/tests.rs b/crates/svg/src/import/text/tests.rs index a6bcf07265..18ec0ec102 100644 --- a/crates/svg/src/import/text/tests.rs +++ b/crates/svg/src/import/text/tests.rs @@ -1,4 +1,5 @@ use super::*; +use vectorcraft_doc::Document; /// The texts [`prepare`] builds from `body` and how many times it read a ``'s path. fn prepared(body: &str) -> (usize, u64, Vec) { @@ -27,3 +28,134 @@ fn uses_of_a_text_on_a_path_read_the_path_once() { )); assert_eq!((texts, reads), (51, 1)); } + +/// How many times [`prepare`] walked the document's elements to find the element a +/// `` names. +fn id_walks(body: &str) -> u64 { + let svg = format!(r#"{body}"#); + let xml = roxmltree::Document::parse(&svg).unwrap(); + let before = ID_WALKS.get(); + prepare(&svg, &xml, None, 96.0, &mut vec![]); + ID_WALKS.get() - before +} + +/// The texts on paths in one file find the elements they name through one walk of the document. +#[test] +fn text_paths_find_their_elements_in_one_walk() { + let paths: String = (0..20).map(|i| format!(r#""#)).collect(); + let texts: String = (0..20).map(|i| format!(r##"Path"##)).collect(); + assert_eq!(id_walks(&format!("{paths}{texts}")), 1); + // Texts shown only through `` elements share the walk, and a missing id needs no other. + let uses: String = (0..20).map(|i| format!(r##""##)).collect(); + let missing = r##"Path"##; + assert_eq!(id_walks(&format!("{paths}{texts}{uses}{missing}")), 1); + // A file whose texts name no element is not walked. + assert_eq!(id_walks(r#"PlainInline"#), 0); + assert_eq!(id_walks(r#"No hash"#), 0); +} + +/// The document and warnings [`crate::import`] gives for `body`, with each ``'s +/// element found through the map of ids or, with `linear`, by walking the document for each one. +fn imported(body: &str, linear: bool) -> (Document, Vec) { + let svg = format!(r#"{body}"#); + LINEAR_IDS.set(linear); + let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES); + LINEAR_IDS.set(false); + out.unwrap_or_else(|e| panic!("{e}")) +} + +/// The text objects of `d`, in paint order. +fn text_objects(d: &Document) -> Vec { + let mut v = vec![]; + d.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + v.push((**t).clone()); + } + }); + v +} + +/// The map of ids finds the element the document walk finds: the first element in document order +/// with the id, whatever it is. +#[test] +fn text_paths_find_the_element_a_document_walk_finds() { + let cases = [ + // Several paths, one of them named twice, and shapes. + r##" + + First + Second + Circle + Rect"##, + // A missing id, an empty one, and one without a `#`. + r##"Missing + EmptyBare"##, + // The first element with the id has no path; the later path is not used. + r##"Group"##, + // Ids on texts and groups, one of them named twice. + r##"SelfLaterGroup"##, + // Uses of texts on paths, and an inline path beside an href. + r##"Used + Inline"##, + ]; + for body in cases { + let map = imported(body, false); + assert_eq!(map, imported(body, true), "{body}"); + assert!(!text_objects(&map.0).is_empty(), "{body}"); + } +} + +/// With two elements of one id, a `` follows the first. +#[test] +fn a_text_path_follows_the_first_element_with_its_id() { + let text = r##"Path"##; + let first = text_objects(&imported(&format!(r#"{text}"#), false).0); + let only = text_objects(&imported(&format!(r#"{text}"#), false).0); + let second = text_objects(&imported(&format!(r#"{text}"#), false).0); + assert!(matches!(first[0].kind, TextKind::OnPath { .. }), "{:?}", first[0].kind); + assert_eq!(first, only); + assert_ne!(first, second); + // A first element with no path leaves the text without one. + let (doc, warnings) = imported(&format!(r#"{text}"#), false); + assert!(!matches!(text_objects(&doc)[0].kind, TextKind::OnPath { .. }), "{warnings:?}"); +} + +/// Times importing a file with 20,000 paths and 2,000 texts on paths, finding each ``'s +/// element through the map of ids and by walking the document for each one, after checking that +/// the two give the same document. Run it with +/// `cargo test --release -p vectorcraft-svg --lib text_path_lookup_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand in a release build"] +fn text_path_lookup_timing() { + let mut body = String::new(); + for i in 0..20_000 { + let _ = write!(body, r#""#, i % 400, i % 400); + if i % 10 == 9 { + let k = (i * 7919) % 20_000; + let _ = write!(body, r##"L{i}"##); + } + } + let svg = format!(r#"{body}"#); + let run = |linear: bool| { + LINEAR_IDS.set(linear); + let start = std::time::Instant::now(); + let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES); + let took = start.elapsed(); + LINEAR_IDS.set(false); + (out.unwrap_or_else(|e| panic!("{e}")), took) + }; + let (map, _) = run(false); + let (walk, _) = run(true); + assert_eq!(map, walk); + assert_eq!(text_objects(&map.0).len(), 2_000); + let (mut maps, mut walks) = (vec![], vec![]); + for _ in 0..7 { + walks.push(run(true).1); + maps.push(run(false).1); + } + println!("walk per textPath: {walks:?}"); + println!("map of ids: {maps:?}"); + walks.sort(); + maps.sort(); + println!("median: walk {:?}, map {:?}", walks[3], maps[3]); +} diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index fa88e3f9ef..c0fc17876a 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -9,6 +9,8 @@ description = "VectorCraft text: font database, shaping, layout, glyph outlines" workspace = true [dependencies] +# The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here). +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 59c99f8901..83c55a71ca 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, RwLock}; use kurbo::BezPath; use skrifa::instance::{Location, LocationRef, Size}; -use skrifa::outline::{DrawSettings, OutlinePen}; +use skrifa::outline::OutlinePen; use skrifa::raw::FileRef; use skrifa::string::StringId; use skrifa::{GlyphId, MetadataProvider, Tag}; @@ -74,7 +74,7 @@ pub use stylistic_sets::StylisticSet; use traits::Alias; #[cfg(test)] use traits::{FaceKeys, face_names}; -pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits}; +pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, is_generic_family}; #[cfg(test)] pub(crate) use traits::{alias_lists, face_styles, on_faces_published}; pub use wanted::{WantedFont, WantedFonts}; diff --git a/crates/text/src/fontdb/glyph_pen.rs b/crates/text/src/fontdb/glyph_pen.rs index fdbb27e3a7..5387ff4b55 100644 --- a/crates/text/src/fontdb/glyph_pen.rs +++ b/crates/text/src/fontdb/glyph_pen.rs @@ -53,6 +53,25 @@ impl OutlinePen for FlipPen { } } +// Share font decoding while preserving the app's existing y-down geometry and resource budget. +impl craft_font_catalog::GlyphPen for FlipPen { + fn move_to(&mut self, x: f32, y: f32) { + OutlinePen::move_to(self, x, y); + } + fn line_to(&mut self, x: f32, y: f32) { + OutlinePen::line_to(self, x, y); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + OutlinePen::quad_to(self, x1, y1, x, y); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + OutlinePen::curve_to(self, x1, y1, x2, y2, x, y); + } + fn close(&mut self) { + OutlinePen::close(self); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 27302aed2f..2e6014fcf4 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -10,10 +10,7 @@ use super::names::{norm, norm_chars, script_families}; #[cfg(not(target_arch = "wasm32"))] use super::scan::{enumerate_faces, font_files}; use super::traits::{Alias, FontMatch, FontTraits, regular_rank}; -use super::{ - Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, - Ordering, Size, -}; +use super::{Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, FontDb, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering}; /// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads. const MAX_POSTSCRIPT_FACES: usize = 16; @@ -368,6 +365,12 @@ impl FontDb { loaded.or_else(|| self.instance_by_id(id)) } + /// The faces loaded so far (the bundled fonts and the installed ones type has used), in load + /// order. Installed fonts that nothing has asked for yet are not among them. + pub fn loaded_faces(&self) -> Vec> { + self.read_faces().clone() + } + /// The face of character style `st`: [`Self::face_version`] of its font, instanced at its /// Variable Font settings ([`Self::instance`]). pub fn style_face(&self, st: &vectorcraft_doc::CharStyle) -> Option> { @@ -654,13 +657,7 @@ impl FontDb { if let Some(p) = self.outlines.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { return p.clone(); } - let mut pen = FlipPen(BezPath::new()); - if let Some(f) = face.skrifa() - && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid)) - { - let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); - } - let p = Arc::new(pen.0); + let p = Arc::new(self.outline_uncached(face, gid)); let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner()); if cache.len() >= OUTLINE_CACHE_MAX { cache.clear(); @@ -669,6 +666,17 @@ impl FontDb { p } + /// [`Self::outline`] without the cache: for reading many glyphs once (Retype's index), which + /// would otherwise push out the outlines the canvas keeps there. + pub fn outline_uncached(&self, face: &FontFace, gid: u32) -> BezPath { + let mut pen = FlipPen(BezPath::new()); + if let Ok(font) = craft_font_catalog::FontOutline::from_bytes(face.data(), face.index(), face.variations()) { + // As before, keep the prefix emitted before a malformed glyph reports an error. + let _ = font.draw_to(gid, &mut pen); + } + pen.0 + } + /// Glyph `gid`'s colour bitmap (`sbix`, `CBDT`) in `face`, cached per (face, glyph). pub fn glyph_image(&self, face: &FontFace, gid: u32) -> Option> { if !face.colour_bitmaps { @@ -722,3 +730,89 @@ impl FontDb { content } } + +#[cfg(test)] +mod shared_outline_tests { + use super::super::glyph_pen::FlipPen; + use super::*; + use skrifa::instance::Size; + use skrifa::outline::DrawSettings; + use skrifa::{GlyphId, MetadataProvider}; + + #[test] + fn shared_outlines_match_original_pen_for_variable_instances() { + let db = FontDb::with_font_dirs(vec![]); + let Some(bytes) = crate::test_fonts::variable_font() else { return }; + assert!(db.add_font(bytes) > 0); + let face = db.face(crate::test_fonts::VARIABLE_FAMILY, "Bold").expect("named instance is registered"); + let f = face.skrifa().expect("font parses"); + for ch in ['A', 'V', ' ', 'a'] { + let Some(glyph) = f.charmap().map(ch) else { continue }; + let mut old = FlipPen(BezPath::new()); + if let Some(outline) = f.outline_glyphs().get(GlyphId::new(glyph.to_u32())) { + // Match the prior production behavior, including a partial path on error. + let _ = outline.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut old); + } + assert_eq!(*db.outline(&face, glyph.to_u32()), old.0, "glyph {ch}"); + } + } + + // Generated CFF keeps the differential tests independent of installed fonts. + fn cff_font(program: &[u8]) -> Vec { + let mut cff = vec![1, 0, 4, 4, 0, 1, 1, 1, 2, b'X', 0, 1, 1, 1, 7, 29, 0, 0, 0, 25, 17, 0, 0, 0, 0]; + cff.extend_from_slice(&[0, 1, 4]); + cff.extend_from_slice(&1u32.to_be_bytes()); + cff.extend_from_slice(&((program.len() as u32) + 1).to_be_bytes()); + cff.extend_from_slice(program); + let mut builder = write_fonts::FontBuilder::new(); + let mut head = vec![0; 54]; + head[18..20].copy_from_slice(&1000u16.to_be_bytes()); + let mut hhea = vec![0; 36]; + hhea[34..36].copy_from_slice(&1u16.to_be_bytes()); + for (tag, data) in [(b"head", head), (b"hhea", hhea), (b"hmtx", vec![0, 100, 0, 0]), (b"maxp", vec![0, 0, 0x50, 0, 0, 1]), (b"CFF ", cff)] { + builder.add_raw(write_fonts::types::Tag::new(tag), data); + } + builder.build() + } + + #[test] + fn malformed_cff_prefix_matches_original_pen() { + let bytes = cff_font(&[139, 139, 21, 239, 139, 5, 10, 14]); + let gid = 0; + let f = skrifa::FontRef::new(&bytes).unwrap(); + let mut old = FlipPen(BezPath::new()); + let result = f + .outline_glyphs() + .get(GlyphId::new(gid)) + .unwrap() + .draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old); + assert!(result.is_err()); + assert!(!old.0.elements().is_empty()); + let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + let mut streamed = FlipPen(BezPath::new()); + assert!(shared.draw_to(gid, &mut streamed).is_err()); + assert_eq!(streamed.0, old.0); + } + + #[test] + fn large_valid_outline_matches_original_pen() { + let mut program = vec![139, 139, 21]; + for _ in 0..100_001 { + program.extend_from_slice(&[140, 6]); + } + program.push(14); + let bytes = cff_font(&program); + let f = skrifa::FontRef::new(&bytes).unwrap(); + let mut old = FlipPen(BezPath::new()); + f.outline_glyphs() + .get(GlyphId::new(0)) + .unwrap() + .draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old) + .unwrap(); + assert!(old.0.elements().len() > 100_000); + let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap(); + let mut streamed = FlipPen(BezPath::new()); + shared.draw_to(0, &mut streamed).unwrap(); + assert_eq!(streamed.0, old.0); + } +} diff --git a/crates/text/src/fontdb/traits.rs b/crates/text/src/fontdb/traits.rs index abcfe863e7..6b6ac5c87e 100644 --- a/crates/text/src/fontdb/traits.rs +++ b/crates/text/src/fontdb/traits.rs @@ -433,6 +433,29 @@ impl FontMatch { } } +/// The CSS generic font families (CSS Fonts Module Level 4), which SVG and HTML files name in place +/// of a font and no font file provides; compared in any ASCII case ([`is_generic_family`]). The +/// list leaves out `fangsong`, which is also the family name of a Chinese font (FangSong). +pub const GENERIC_FAMILIES: &[&str] = &[ + "serif", + "sans-serif", + "monospace", + "cursive", + "fantasy", + "system-ui", + "ui-serif", + "ui-sans-serif", + "ui-monospace", + "ui-rounded", + "math", + "emoji", +]; + +/// Whether `family` (surrounding spaces ignored) is one of the [`GENERIC_FAMILIES`], in any ASCII case. +pub fn is_generic_family(family: &str) -> bool { + GENERIC_FAMILIES.iter().any(|g| g.eq_ignore_ascii_case(family.trim())) +} + /// A face's (family, style) names. pub(super) fn face_names(f: &skrifa::FontRef<'_>) -> Option<(String, String)> { let family = name(f, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME])?; diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 7a7c904591..04e594ed16 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -62,30 +62,22 @@ fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool { /// ([`upright_extent`]) as a share of `upright`, the length in font units its own width runs down. /// Empty for a glyph of one character. fn ligature_carets(text: &str, g: &SGlyph, rtl: bool, upright: Option) -> Vec<(usize, f64)> { - use unicode_segmentation::UnicodeSegmentation; - let Some(s) = text.get(g.byte..g.byte + g.len).filter(|_| g.len > 1) else { return Vec::new() }; - let starts: Vec = s.grapheme_indices(true).skip(1).map(|(i, _)| g.byte + i).collect(); - if starts.is_empty() { - return Vec::new(); - } - let parts = starts.len() + 1; - let from_font = if let Some(length) = upright { - let (cell, top) = upright_extent(g); - g.face - .vertical_ligature_carets(g.gid, starts.len(), top, cell) - .filter(|c| c.len() == starts.len() && length > 0.0) - .map(|c| c.into_iter().map(|d| d / length).collect::>()) - .filter(|c| c.iter().all(|f| *f > 0.0 && *f < 1.0)) - } else { - let advance = g.face.advance(g.gid); - g.face - .ligature_carets(g.gid, starts.len()) - .filter(|c| c.len() == starts.len() && advance > 0.0) - .map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::>()) - }; - let mut at = from_font.unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect()); - at.sort_by(f64::total_cmp); - starts.into_iter().zip(at).collect() + craft_font_catalog::ligature_caret_stops(text, g.byte, g.len, |count| { + if let Some(length) = upright { + let (cell, top) = upright_extent(g); + g.face + .vertical_ligature_carets(g.gid, count, top, cell) + .filter(|c| c.len() == count && length > 0.0) + .map(|c| c.into_iter().map(|d| d / length).collect::>()) + .filter(|c| c.iter().all(|f| *f > 0.0 && *f < 1.0)) + } else { + let advance = g.face.advance(g.gid); + g.face + .ligature_carets(g.gid, count) + .filter(|c| c.len() == count && advance > 0.0) + .map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::>()) + } + }) } /// Does glyph `g`, standing upright in vertical type, take a cell of its own down the column? Every diff --git a/crates/text/src/layout/bidi.rs b/crates/text/src/layout/bidi.rs index 3f9872983d..e4574c42d4 100644 --- a/crates/text/src/layout/bidi.rs +++ b/crates/text/src/layout/bidi.rs @@ -81,34 +81,9 @@ pub(super) fn visual_order(bidi: Option<&BidiInfo<'_>>, paragraph_start: usize, return vec![]; } let levels = bidi.reordered_levels(para, line.start.saturating_sub(paragraph_start)..line.end.saturating_sub(paragraph_start)); - // A list marker (length 0) is a cluster of its own. - let mut clusters: Vec> = Vec::new(); - for (i, g) in glyphs.iter().enumerate() { - if i > 0 && glyphs.get(i - 1).is_some_and(|p| p.byte == g.byte && (p.len == 0) == (g.len == 0)) { - if let Some(c) = clusters.last_mut() { - c.end = i + 1; - } - } else { - clusters.push(i..i + 1); - } - } - // A list marker is at the paragraph's level, and at a right-to-left one its tab is drawn - // before (left of) its characters. - let cluster_levels: Vec<_> = clusters - .iter() - .filter_map(|c| glyphs.get(c.start)) - .map(|g| if g.len == 0 { g.level } else { levels.get(g.byte.saturating_sub(paragraph_start)).copied().unwrap_or(g.level) }) - .collect(); - let reversed = |i: usize| glyphs.get(clusters.get(i).map_or(0, |c| c.start)).is_some_and(|g| g.len == 0 && g.level.is_rtl()); - unicode_bidi::BidiInfo::reorder_visual(&cluster_levels) - .into_iter() - .filter_map(|i| clusters.get(i).map(|c| (c.clone(), reversed(i)))) - .flat_map(|(c, rev)| { - let mut v: Vec = c.collect(); - if rev { - v.reverse(); - } - v - }) - .collect() + craft_font_catalog::visual_order( + glyphs.iter().map(|g| craft_font_catalog::VisualGlyph { byte: g.byte, len: g.len, level: g.level }), + paragraph_start, + &levels, + ) } diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 375bc343a2..874813e9b1 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -458,24 +458,8 @@ pub(super) fn break_line( line_end: &[f64], fits: Option<&dyn Fn(usize, bool) -> bool>, ) -> (usize, bool) { - // The line ending at `chosen`, once it holds a tab, when it fits as drawn; otherwise the latest - // of the legal `breaks` before it that fits as drawn, measuring at most `checks` of them from - // the latest back and bisecting the earlier ones without a hyphen; the first of them when none - // of those measured fits. - let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| -> (usize, bool) { - let Some(fits) = fits.filter(|_| tabbed) else { return chosen }; - if fits(chosen.0, chosen.1) { - return chosen; - } - let earlier = breaks.get(breaks.partition_point(|b| b.0 <= i)..breaks.partition_point(|b| b.0 < chosen.0)).unwrap_or_default(); - if let Some(&b) = earlier.iter().rev().take(checks).find(|b| fits(b.0, b.1)) { - return b; - } - // Without a hyphen, a line that ends later is drawn no narrower, so those breaks bisect. - let rest = earlier.get(..earlier.len().saturating_sub(checks)).unwrap_or_default(); - let plain: Vec<&(usize, bool)> = rest.iter().filter(|b| !b.1).collect(); - let fitting = plain.partition_point(|b| fits(b.0, b.1)); - fitting.checked_sub(1).and_then(|k| plain.get(k).copied()).or(earlier.first()).copied().unwrap_or(chosen) + let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| { + craft_font_catalog::settle_line_break(tabbed, checks, i, chosen, breaks, fits) }; // How many breaks a line measures as drawn one by one. let checks = |back: f64| if back > 0.0 { MAX_DRAWN_CHECKS_STEPPING_BACK } else { MAX_DRAWN_CHECKS }; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index f7f5d128ba..6d99928b73 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -26,6 +26,7 @@ mod justify; mod kashida; mod kept; mod layout; +pub mod retype; mod shape; #[cfg(not(target_arch = "wasm32"))] mod suitcase; @@ -41,10 +42,10 @@ pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; pub use fontdb::{ - CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphCategory, - GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, - StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, - set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, + CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, + GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, RECENTLY_ADDED_WITHIN, + RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_generic_family, is_suitcase, + set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs new file mode 100644 index 0000000000..4c636aa1cd --- /dev/null +++ b/crates/text/src/retype.rs @@ -0,0 +1,911 @@ +//! Retype's glyph matching (Type › Retype, #4934): which glyph of which loaded font an outlined +//! glyph's shape is, the same up to uniform scale, rotation and translation. +//! +//! Phase 1 is exact matching only. Each contour is read from a starting corner that does not +//! depend on where the path happens to start (the corner farthest from the shape's corners' +//! centre; every such corner is tried when several tie), with straight edges split in two read as +//! one. Points sampled at equal steps of arc length along the contours shortlist the glyphs whose +//! best similarity transform (a Procrustes fit) leaves a tiny leftover distance, and the whole +//! outline, turned onto the shape, must then lie on it. That holds for outlines made from a font +//! the app has (Create Outlines' output, and other apps' that keep each glyph's contours whole and +//! in the font's order). Near matches (other versions of a font, hinted or simplified outlines, +//! faux styles, glyphs merged into one path) are left unmatched; fuzzy identification is phase 2. + +use std::collections::{BTreeSet, HashMap}; +use std::sync::Arc; + +use kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathEl, PathSeg, Point, QuadBez, Shape}; + +use crate::{FontDb, FontFace}; + +/// At most this many faces are indexed. +pub const MAX_FACES: usize = 96; +/// At most this many encoded characters of one face are indexed (in code point order). +pub const MAX_GLYPHS_PER_FACE: usize = 65_536; +/// At most this many glyphs are indexed in all: faces past it are left out. +pub const MAX_GLYPHS: usize = 262_144; +/// Shapes with more path elements than this are not matched. +pub const MAX_ELEMENTS: usize = 4096; +/// Shapes (and glyphs) with more contours than this are not matched. +const MAX_CONTOURS: usize = 48; +/// Points sampled along each contour. +const SAMPLES: usize = 32; +/// The most readings of a shape (one per choice of tied starting corners) that are tried. +const MAX_VARIANTS: usize = 64; +/// The largest leftover distance (root mean square over the samples) for a match, as a fraction of +/// the shape's spread about its centre. +const TOLERANCE: f64 = 2e-3; +/// How far the whole outline, turned onto the shape, may lie from it (both ways), as a fraction of +/// the shape's spread. +const OUTLINE_TOLERANCE: f64 = 5e-3; +/// Points of a flattened outline past which the whole-outline check gives up (and so rejects). +const MAX_OUTLINE_POINTS: usize = 8192; +/// Points along an outline past which the whole-outline check gives up (and so rejects). +const MAX_CHECKED_POINTS: usize = 65_536; +/// The most glyphs one shape is reported to be ([`RetypeIndex::matches`]). +pub const MAX_CANDIDATES: usize = 16; +/// How far apart two shapes' spread-to-length ratios may be and still be compared. +const INVARIANT_SLACK: f64 = 0.02; + +/// One glyph an outlined shape matched. +#[derive(Clone)] +pub struct GlyphMatch { + pub face: Arc, + pub gid: u32, + /// The character the face's cmap maps to the glyph (the lowest, when several do). + pub ch: char, + /// Document units per font unit: the font size is `scale` × units per em. + pub scale: f64, + /// The glyph's turn, radians (as [`kurbo::Affine::rotate`] turns). + pub angle: f64, + /// Where the glyph's origin (its baseline start) lies. + pub origin: Point, + /// The leftover distance, relative to the shape's spread. + pub residual: f64, + /// How many contours the glyph has. + pub contours: usize, + /// Other poses the glyph fits the shape in equally (a glyph that looks the same turned). + pub alts: Vec, +} + +/// Where and how a glyph lies: its size, turn and origin. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + /// Document units per font unit. + pub scale: f64, + /// Radians, as [`kurbo::Affine::rotate`] turns. + pub angle: f64, + /// Where the glyph's origin lies. + pub origin: Point, +} + +impl GlyphMatch { + /// This match in each pose it fits: its own first, then [`Self::alts`]. + pub fn poses(&self) -> impl Iterator + '_ { + let own = Pose { scale: self.scale, angle: self.angle, origin: self.origin }; + std::iter::once(own).chain(self.alts.iter().copied()).map(move |p| GlyphMatch { + scale: p.scale, + angle: p.angle, + origin: p.origin, + ..self.clone() + }) + } +} + +/// A shape reduced for matching: points along each contour, centred. +struct Signature { + contours: usize, + /// Centred points, [`SAMPLES`] per contour. + pts: Vec, + centre: Point, + /// Root mean square distance of the points from the centre. + spread: f64, + /// `spread` / the total contour length: unchanged by scale, turn and move. + invariant: f64, +} + +struct Entry { + face: usize, + gid: u32, + ch: char, + sig: Signature, + /// The glyph's outline in font units, for the whole-outline check. + outline: BezPath, +} + +/// The glyphs of a set of faces, ready to match shapes against. +#[derive(Default)] +pub struct RetypeIndex { + faces: Vec>, + entries: Vec, + /// Entry indices by contour count, sorted by invariant. + buckets: HashMap>, +} + +impl RetypeIndex { + /// Index the outline glyphs of `faces` (the first [`MAX_FACES`], each face once) whose + /// [`shape_key`] is in `keys` (the selected shapes' keys): the others could match no shape, so + /// they are not sampled. Outlines are read past the shared outline cache, which keeps the + /// canvas's glyphs. + pub fn build(db: &FontDb, faces: impl IntoIterator>, keys: &BTreeSet) -> Self { + let mut kept: Vec> = vec![]; + for f in faces { + if kept.len() >= MAX_FACES { + break; + } + if !kept.iter().any(|k| k.id() == f.id()) { + kept.push(f); + } + } + let mut entries = vec![]; + 'faces: for (fi, face) in kept.iter().enumerate() { + for &(gid, ch, key) in face_keys(db, face).iter() { + // The budget holds inside a face too: no glyph is sampled past it. + if entries.len() >= MAX_GLYPHS { + break 'faces; + } + if !keys.contains(&key) { + continue; + } + let outline = db.outline_uncached(face, gid); + if let Some(sig) = signatures(&outline, false).into_iter().next() { + entries.push(Entry { face: fi, gid, ch, sig, outline }); + } + } + } + let mut buckets: HashMap> = HashMap::new(); + for (i, e) in entries.iter().enumerate() { + buckets.entry(e.sig.contours).or_default().push(i); + } + for list in buckets.values_mut() { + list.sort_by(|a, b| { + let (x, y) = (entries.get(*a).map_or(0.0, |e| e.sig.invariant), entries.get(*b).map_or(0.0, |e| e.sig.invariant)); + x.total_cmp(&y) + }); + } + RetypeIndex { faces: kept, entries, buckets } + } + + /// The faces indexed. + pub fn faces(&self) -> &[Arc] { + &self.faces + } + + /// How many glyphs are indexed. + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// The glyphs `shape` (in document space) is: every glyph that fits it exactly, upright ones + /// first, then the closest; empty when it is no glyph of the indexed faces. One shape can be + /// several glyphs: an L, and a turned L (U+A780) turned half round; a u, and an n upside down. + /// A glyph that looks the same turned (an I, an O, a hyphen) also fits in more than one pose: + /// the upright-most comes first and the others are kept in [`GlyphMatch::alts`]. The line + /// around the shape chooses among them. At most [`MAX_CANDIDATES`]. + pub fn matches(&self, shape: &BezPath) -> Vec { + let variants = signatures(shape, true); + let Some(first) = variants.first() else { return vec![] }; + let Some(list) = self.buckets.get(&first.contours) else { return vec![] }; + let lo = first.invariant * (1.0 - INVARIANT_SLACK); + let hi = first.invariant * (1.0 + INVARIANT_SLACK); + let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); + let tol = first.spread * OUTLINE_TOLERANCE; + // The shape flattened for the whole-outline check, once, when a glyph first gets that far. + let mut shape_flat: Option> = None; + let mut out: Vec<(usize, GlyphMatch)> = vec![]; + for i in list.iter().skip(start) { + let Some(e) = self.entries.get(*i) else { continue }; + if e.sig.invariant > hi { + break; + } + let Some(face) = self.faces.get(e.face) else { continue }; + // Each reading of the shape (its tied starting corners) that fits the glyph is a pose. + let mut poses: Vec<(Pose, f64)> = vec![]; + for sig in &variants { + let Some((z, residual)) = fit(&e.sig, sig) else { continue }; + if residual > TOLERANCE { + continue; + } + // The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre. + let gc = mul(z, e.sig.centre); + let pose = Pose { scale: z.0.hypot(z.1), angle: z.1.atan2(z.0), origin: Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y) }; + if poses.iter().any(|(p, _)| wrapped(p.angle - pose.angle).abs() < 1e-6) { + continue; + } + // The samples can step over a detail (a notch between two of them): the whole + // outline, turned onto the shape, must lie on it. + let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); + let Some(flat) = flat.as_ref() else { break }; + let onto = Affine::new([z.0, z.1, -z.1, z.0, pose.origin.x, pose.origin.y]); + if !Flat::new(&(onto * e.outline.clone()), tol).is_some_and(|g| g.agrees(flat)) { + continue; + } + poses.push((pose, residual)); + } + // The upright-most pose first. + poses.sort_by(|a, b| wrapped(a.0.angle).abs().total_cmp(&wrapped(b.0.angle).abs())); + let Some(((pose, _), rest)) = poses.split_first() else { continue }; + let residual = poses.iter().map(|(_, r)| *r).fold(f64::INFINITY, f64::min); + let m = GlyphMatch { + face: face.clone(), + gid: e.gid, + ch: e.ch, + scale: pose.scale, + angle: pose.angle, + origin: pose.origin, + residual, + contours: e.sig.contours, + alts: rest.iter().map(|(p, _)| *p).collect(), + }; + out.push((e.face, m)); + } + let upright = |m: &GlyphMatch| wrapped(m.angle).abs() >= 1e-3; + out.sort_by(|a, b| { + upright(&a.1).cmp(&upright(&b.1)).then(a.1.residual.total_cmp(&b.1.residual)).then(a.0.cmp(&b.0)).then(a.1.ch.cmp(&b.1.ch)) + }); + out.truncate(MAX_CANDIDATES); + out.into_iter().map(|(_, m)| m).collect() + } +} + +/// `a` wrapped into −π..π. +fn wrapped(a: f64) -> f64 { + (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI +} + +/// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`]), one per glyph +/// under the lowest character that maps to it. +type FaceKeys = Arc>; + +/// How many glyph keys [`face_keys`] keeps in all (16 bytes each). +const KEPT_KEYS: usize = 1 << 20; + +/// The faces' keys [`face_keys`] keeps, for the database generation they were read in. +#[derive(Default)] +struct KeptKeys { + generation: u64, + glyphs: usize, + faces: HashMap<(u64, u32), FaceKeys>, +} + +/// [`FaceKeys`] of `face`, worked out once per face (each glyph drawn once, past the outline +/// cache) and kept: a later Retype samples only the glyphs whose key a selected shape has. Keys +/// already kept stay while new faces' keys would not fit, so a run over more faces than fit still +/// finds the same ones kept the next time; they are let go when fonts are added or rescanned. +fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { + static KEPT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let kept = KEPT.get_or_init(Default::default); + let at = (db.id(), face.id()); + let generation = db.generation(); + { + let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); + if k.generation != generation { + *k = KeptKeys { generation, ..Default::default() }; + } + if let Some(keys) = k.faces.get(&at) { + return keys.clone(); + } + } + let mut by_gid: HashMap = HashMap::new(); + for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { + if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { + continue; + } + by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); + } + let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); + gids.sort_unstable(); + let keys: FaceKeys = Arc::new(gids.into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect()); + let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); + if k.generation != generation { + return keys; + } + // Another Retype may have worked them out meanwhile: keep and charge one list. + if let Some(already) = k.faces.get(&at) { + return already.clone(); + } + if k.glyphs + keys.len() <= KEPT_KEYS { + k.glyphs += keys.len(); + k.faces.insert(at, keys.clone()); + } + keys +} + +/// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy +/// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same +/// shape as one of them, so matching them would turn art into text. They are not matched. +fn is_shape_symbol(c: char) -> bool { + matches!( + u32::from(c), + 0x2500..=0x25FF | 0x2B00..=0x2BFF | 0x1F780..=0x1F7FF | 0x1FB00..=0x1FBFF | 0xE000..=0xF8FF | 0xF0000..=0x10FFFF + ) +} + +/// Complex multiply: `z` (a scaled turn) applied to `p`. +fn mul(z: (f64, f64), p: Point) -> Point { + Point::new(z.0 * p.x - z.1 * p.y, z.1 * p.x + z.0 * p.y) +} + +/// The scaled turn `z` that best takes glyph `g`'s points onto shape `s`'s (both centred), and the +/// leftover distance relative to the shape's spread; `None` for degenerate shapes. +fn fit(g: &Signature, s: &Signature) -> Option<((f64, f64), f64)> { + if g.pts.len() != s.pts.len() || g.pts.is_empty() { + return None; + } + let (mut re, mut im, mut gg) = (0.0, 0.0, 0.0); + for (a, b) in g.pts.iter().zip(&s.pts) { + // Σ s · conj(g) + re += b.x * a.x + b.y * a.y; + im += b.y * a.x - b.x * a.y; + gg += a.x * a.x + a.y * a.y; + } + if gg <= 0.0 || !gg.is_finite() { + return None; + } + let z = (re / gg, im / gg); + let mut res = 0.0; + for (a, b) in g.pts.iter().zip(&s.pts) { + let p = mul(z, *a); + res += (p.x - b.x).powi(2) + (p.y - b.y).powi(2); + } + let n = s.pts.len() as f64; + let rel = (res / n).sqrt() / s.spread; + rel.is_finite().then_some((z, rel)) +} + +/// An outline flattened for the whole-outline check: its segments, points along them (every +/// corner, and points twice `tol` apart between corners: a detail narrower than that has corners +/// of its own), and a uniform grid listing each segment under every cell its box, grown by `tol`, +/// touches, so whether a point lies within `tol` of the outline is asked of the few segments +/// around it. +struct Flat { + segs: Vec<(Point, Point)>, + pts: Vec, + origin: Point, + cell: f64, + cols: usize, + rows: usize, + /// Segment indices per cell, row by row. + cells: Vec>, + tol: f64, +} + +impl Flat { + /// Cells along the longer side, at most. + const MAX_SIDE: f64 = 48.0; + /// Segment listings in all, at most: past it (or past [`MAX_OUTLINE_POINTS`] segments or + /// [`MAX_CHECKED_POINTS`] points), `None`, and so no match. + const MAX_LISTINGS: usize = 1 << 18; + + fn new(path: &BezPath, tol: f64) -> Option { + if !tol.is_finite() || tol <= 0.0 { + return None; + } + let mut segs = vec![]; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + let mut too_many = false; + kurbo::flatten(path.iter(), tol / 2.0, |el| { + if segs.len() > MAX_OUTLINE_POINTS { + too_many = true; + return; + } + match el { + PathEl::MoveTo(q) => (start, last) = (q, q), + PathEl::LineTo(q) => { + segs.push((last, q)); + last = q; + } + PathEl::ClosePath => { + segs.push((last, start)); + last = start; + } + _ => {} + } + }); + if too_many { + return None; + } + let mut pts = vec![]; + for (s, e) in &segs { + let steps = (s.distance(*e) / (2.0 * tol)).ceil(); + if !steps.is_finite() || pts.len() as f64 + steps > MAX_CHECKED_POINTS as f64 { + return None; + } + let steps = (steps as usize).max(1); + pts.extend((0..steps).map(|i| s.lerp(*e, i as f64 / steps as f64))); + } + let (first, _) = segs.first()?; + let mut bb = kurbo::Rect::from_points(*first, *first); + for (s, e) in &segs { + bb = bb.union_pt(*s).union_pt(*e); + } + let bb = bb.inflate(tol, tol); + let cell = (bb.width().max(bb.height()) / Self::MAX_SIDE).max(2.0 * tol); + if !cell.is_finite() || cell <= 0.0 { + return None; + } + let at = |v: f64, o: f64| (((v - o) / cell).floor().max(0.0) as usize).min(Self::MAX_SIDE as usize); + let (cols, rows) = (at(bb.x1, bb.x0) + 1, at(bb.y1, bb.y0) + 1); + let mut cells: Vec> = vec![vec![]; cols * rows]; + let mut listings = 0usize; + for (i, (s, e)) in segs.iter().enumerate() { + let r = kurbo::Rect::from_points(*s, *e).inflate(tol, tol); + for cy in at(r.y0, bb.y0)..=at(r.y1, bb.y0).min(rows - 1) { + for cx in at(r.x0, bb.x0)..=at(r.x1, bb.x0).min(cols - 1) { + listings += 1; + if listings > Self::MAX_LISTINGS { + return None; + } + if let Some(c) = cells.get_mut(cy * cols + cx) { + c.push(u32::try_from(i).ok()?); + } + } + } + } + Some(Flat { segs, pts, origin: Point::new(bb.x0, bb.y0), cell, cols, rows, cells, tol }) + } + + /// Does `p` lie within `tol` of a segment? + fn near(&self, p: Point) -> bool { + let (fx, fy) = ((p.x - self.origin.x) / self.cell, (p.y - self.origin.y) / self.cell); + if !(fx >= 0.0 && fy >= 0.0) || fx >= self.cols as f64 || fy >= self.rows as f64 { + return false; + } + let (cx, cy) = (fx as usize, fy as usize); + let tol2 = self.tol * self.tol; + self.cells.get(cy * self.cols + cx).is_some_and(|list| { + list.iter().filter_map(|i| self.segs.get(*i as usize)).any(|(s, e)| Line::new(*s, *e).nearest(p, 1e-9).distance_sq <= tol2) + }) + } + + /// Do the two outlines lie on each other: every point of each within `tol` of the other? + fn agrees(&self, other: &Flat) -> bool { + self.pts.iter().all(|p| other.near(*p)) && other.pts.iter().all(|p| self.near(*p)) + } +} + +/// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within +/// `tol` of the other? `false` when either is too large to check. +#[cfg(test)] +fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { + matches!((Flat::new(a, tol), Flat::new(b, tol)), (Some(fa), Some(fb)) if fa.agrees(&fb)) +} + +/// `seg` as a line when it is one (a curve with its handles on its ends or on its line), else as it is. +fn as_line(seg: PathSeg) -> PathSeg { + let on_line = |a: Point, b: Point, p: Point| { + let ab = b - a; + let len = ab.hypot(); + len > 0.0 && (ab.cross(p - a)).abs() <= len * len * 1e-12 && (p - a).dot(ab) >= 0.0 && (p - b).dot(ab) <= 0.0 + }; + match seg { + PathSeg::Quad(q) if q.p1 == q.p0 || q.p1 == q.p2 || on_line(q.p0, q.p2, q.p1) => PathSeg::Line(Line::new(q.p0, q.p2)), + PathSeg::Cubic(c) if (c.p1 == c.p0 || on_line(c.p0, c.p3, c.p1)) && (c.p2 == c.p3 || on_line(c.p0, c.p3, c.p2)) => { + PathSeg::Line(Line::new(c.p0, c.p3)) + } + s => s, + } +} + +/// Lines `a` then `b` run on in one direction: one edge split in two. +fn runs_on(a: &PathSeg, b: &PathSeg) -> bool { + let (PathSeg::Line(a), PathSeg::Line(b)) = (a, b) else { return false }; + let (u, v) = (a.p1 - a.p0, b.p1 - b.p0); + let (lu, lv) = (u.hypot(), v.hypot()); + lu > 0.0 && lv > 0.0 && u.cross(v).abs() <= lu * lv * 1e-9 && u.dot(v) > 0.0 +} + +/// `path`'s contours as segments, the closing line included, read the same however the path was +/// written: segments that go nowhere are dropped, curves that are straight read as lines, and a +/// straight edge split in two (around the start too) reads as one. `None` past the size caps. +fn contours(path: &BezPath) -> Option>> { + if path.elements().len() > MAX_ELEMENTS { + return None; + } + let mut out: Vec> = vec![]; + let mut cur: Vec = vec![]; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + let push = |cur: &mut Vec, seg: PathSeg| { + let seg = as_line(seg); + if seg.start() == seg.end() && matches!(seg, PathSeg::Line(_)) { + return; + } + match cur.last_mut() { + Some(prev) if runs_on(prev, &seg) => *prev = PathSeg::Line(Line::new(prev.start(), seg.end())), + _ => cur.push(seg), + } + }; + let flush = |cur: &mut Vec, start: Point, last: Point, out: &mut Vec>| { + if last.distance(start) > 0.0 { + push(cur, PathSeg::Line(Line::new(last, start))); + } + // An edge split at the contour's start: its two halves are the last and first segments. + if cur.len() > 1 + && let (Some(l), Some(f)) = (cur.last().copied(), cur.first().copied()) + && runs_on(&l, &f) + { + cur.pop(); + if let Some(first) = cur.first_mut() { + *first = PathSeg::Line(Line::new(l.start(), f.end())); + } + } + if !cur.is_empty() { + out.push(std::mem::take(cur)); + } + }; + for el in path.elements() { + match *el { + PathEl::MoveTo(p) => { + flush(&mut cur, start, last, &mut out); + start = p; + last = p; + } + PathEl::LineTo(p) => { + push(&mut cur, PathSeg::Line(Line::new(last, p))); + last = p; + } + PathEl::QuadTo(a, p) => { + push(&mut cur, PathSeg::Quad(QuadBez::new(last, a, p))); + last = p; + } + PathEl::CurveTo(a, b, p) => { + push(&mut cur, PathSeg::Cubic(CubicBez::new(last, a, b, p))); + last = p; + } + PathEl::ClosePath => { + flush(&mut cur, start, last, &mut out); + last = start; + } + } + if out.len() > MAX_CONTOURS { + return None; + } + } + flush(&mut cur, start, last, &mut out); + (out.len() <= MAX_CONTOURS).then_some(out) +} + +/// A cheap key two shapes share when one is the other scaled, turned and moved: how many segments +/// each of its contours has, in order, as [`contours`] reads them, hashed. Glyphs whose key no +/// selected shape has are not sampled. `None` past the size caps or for an empty shape. +pub fn shape_key(path: &BezPath) -> Option { + let cs = contours(path)?; + if cs.is_empty() { + return None; + } + // FNV-1a over the counts: equal keys for equal counts; a rare clash only samples a glyph more. + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for n in std::iter::once(cs.len()).chain(cs.iter().map(Vec::len)) { + for b in (n as u64).to_le_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + } + Some(h) +} + +/// `path` read for matching: one reading per choice of starting corners (the corner of each contour +/// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the +/// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. +fn signatures(path: &BezPath, all_ties: bool) -> Vec { + let bounds = path.bounding_box(); + let size = bounds.width().hypot(bounds.height()); + if !size.is_finite() || size <= 0.0 { + return vec![]; + } + let accuracy = size * 1e-6; + let Some(cs) = contours(path) else { return vec![] }; + // Each contour with length, with its segments' lengths. + let cs: Vec<(Vec, Vec)> = cs + .into_iter() + .map(|c| { + let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); + (c, lens) + }) + .filter(|(_, lens)| { + let len: f64 = lens.iter().sum(); + len.is_finite() && len > size * 1e-9 + }) + .collect(); + let corners: Vec = cs.iter().flat_map(|(c, _)| c.iter().map(|s| s.start())).collect(); + if corners.is_empty() { + return vec![]; + } + let n = corners.len() as f64; + let mid = Point::new(corners.iter().map(|p| p.x).sum::() / n, corners.iter().map(|p| p.y).sum::() / n); + // Each contour's starting corners: those farthest from `mid`, ties within a hair. + let starts: Vec> = cs + .iter() + .map(|(c, _)| { + let d: Vec = c.iter().map(|s| s.start().distance(mid)).collect(); + let far = d.iter().copied().fold(0.0, f64::max); + let tied: Vec = d.iter().enumerate().filter(|(_, v)| **v >= far - size * 1e-7).map(|(i, _)| i).collect(); + if all_ties { tied } else { tied.into_iter().take(1).collect() } + }) + .collect(); + let mut out = vec![]; + let mut pick = vec![0usize; cs.len()]; + // Readings tried, kept or not: a shape whose readings all fail (its sums run past what f64 + // holds) tries no more than this either. + let mut tried = 0usize; + loop { + if tried >= MAX_VARIANTS { + break; + } + tried += 1; + if let Some(sig) = sample(&cs, &starts, &pick, accuracy) { + out.push(sig); + } + // The next choice of tied corners (a counter in mixed radix). + let mut i = 0; + loop { + let Some((p, s)) = pick.get_mut(i).zip(starts.get(i)) else { return out }; + *p += 1; + if *p < s.len() { + break; + } + *p = 0; + i += 1; + } + } + out +} + +/// One reading of the contours `cs`, contour `i` starting at segment `starts[i][pick[i]]`. +fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize], accuracy: f64) -> Option { + let mut pts = Vec::with_capacity(cs.len() * SAMPLES); + let mut total = 0.0; + for (((c, lens), s), p) in cs.iter().zip(starts).zip(pick) { + let from = *s.get(*p)?; + let m = c.len(); + let len: f64 = lens.iter().sum(); + total += len; + let (mut k, mut before) = (0usize, 0.0); + let at_k = |k: usize| (from + k) % m; + for j in 0..SAMPLES { + let at = len * j as f64 / SAMPLES as f64; + while k + 1 < m && before + lens.get(at_k(k)).copied().unwrap_or(0.0) < at { + before += lens.get(at_k(k)).copied().unwrap_or(0.0); + k += 1; + } + let (Some(seg), Some(l)) = (c.get(at_k(k)), lens.get(at_k(k))) else { return None }; + let t = if *l > 0.0 { seg.inv_arclen((at - before).clamp(0.0, *l), accuracy) } else { 0.0 }; + pts.push(seg.eval(t)); + } + } + if pts.is_empty() { + return None; + } + let n = pts.len() as f64; + let centre = Point::new(pts.iter().map(|p| p.x).sum::() / n, pts.iter().map(|p| p.y).sum::() / n); + for p in &mut pts { + *p = Point::new(p.x - centre.x, p.y - centre.y); + } + let spread = (pts.iter().map(|p| p.x * p.x + p.y * p.y).sum::() / n).sqrt(); + if !spread.is_finite() || spread <= 0.0 || !total.is_finite() || total <= 0.0 { + return None; + } + Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total }) +} + +/// The first reading of `path` (for tests). +#[cfg(test)] +fn signature(path: &BezPath) -> Option { + signatures(path, false).into_iter().next() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn letter() -> BezPath { + // A hand-made "P"-like shape: an outer contour and a counter. + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((0.0, -700.0)); + p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0)); + p.quad_to((450.0, -300.0), (120.0, -300.0)); + p.line_to((120.0, 0.0)); + p.close_path(); + p.move_to((120.0, -600.0)); + p.line_to((120.0, -400.0)); + p.quad_to((330.0, -400.0), (330.0, -500.0)); + p.quad_to((330.0, -600.0), (120.0, -600.0)); + p.close_path(); + p + } + + #[test] + fn a_shape_matches_itself_scaled_turned_and_moved() { + let g = signature(&letter()).unwrap(); + let xf = Affine::translate((300.0, 200.0)) * Affine::rotate(0.4) * Affine::scale(0.024); + let s = signature(&(xf * letter())).unwrap(); + let (z, res) = fit(&g, &s).unwrap(); + assert!(res < 1e-6, "{res}"); + assert!((z.0.hypot(z.1) - 0.024).abs() < 1e-9); + assert!((z.1.atan2(z.0) - 0.4).abs() < 1e-9); + let origin = s.centre - mul(z, g.centre).to_vec2(); + assert!(origin.distance(Point::new(300.0, 200.0)) < 1e-6, "{origin:?}"); + } + + #[test] + fn lines_written_as_curves_still_match() { + // Paths store lines as cubics with handles on their anchors, or the closing line explicitly. + let mut alt = BezPath::new(); + alt.move_to((0.0, 0.0)); + alt.curve_to((0.0, 0.0), (0.0, -700.0), (0.0, -700.0)); + alt.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0)); + alt.extend([PathEl::QuadTo((450.0, -300.0).into(), (120.0, -300.0).into())]); + alt.line_to((120.0, 0.0)); + alt.line_to((0.0, 0.0)); + alt.close_path(); + alt.move_to((120.0, -600.0)); + alt.line_to((120.0, -400.0)); + alt.quad_to((330.0, -400.0), (330.0, -500.0)); + alt.quad_to((330.0, -600.0), (120.0, -600.0)); + alt.close_path(); + let (_, res) = fit(&signature(&letter()).unwrap(), &signature(&alt).unwrap()).unwrap(); + assert!(res < 1e-6, "{res}"); + } + + #[test] + fn another_shape_does_not_match() { + let mut o = BezPath::new(); + o.extend(kurbo::Circle::new((200.0, -350.0), 300.0).path_elements(0.1)); + let mut box_ = BezPath::new(); + box_.extend(kurbo::Rect::new(0.0, -700.0, 450.0, 0.0).path_elements(0.1)); + let (a, b) = (signature(&o).unwrap(), signature(&box_).unwrap()); + assert!(fit(&a, &b).is_none_or(|(_, r)| r > TOLERANCE)); + } + + #[test] + fn plain_shape_symbols_are_not_matched() { + // A block element (U+1FB89) drew as a rectangle and took a drawn rectangle for it. + for c in ['\u{1FB89}', '\u{25A0}', '\u{2588}', '\u{E000}'] { + assert!(is_shape_symbol(c), "{c:?}"); + } + for c in ['A', 'l', '-', '\u{6F22}', '\u{0915}'] { + assert!(!is_shape_symbol(c), "{c:?}"); + } + } + + #[test] + fn degenerate_and_hostile_shapes_give_none() { + assert!(signature(&BezPath::new()).is_none()); + let mut dot = BezPath::new(); + dot.move_to((5.0, 5.0)); + dot.close_path(); + assert!(signature(&dot).is_none()); + let mut nan = BezPath::new(); + nan.move_to((f64::NAN, 0.0)); + nan.line_to((1.0, 1.0)); + assert!(signature(&nan).is_none()); + let mut huge = BezPath::new(); + huge.move_to((0.0, 0.0)); + for i in 0..(MAX_ELEMENTS + 1) { + huge.line_to((i as f64, (i % 7) as f64)); + } + assert!(signature(&huge).is_none()); + } + + /// The best fit of `shape`'s readings onto `glyph`'s first one. + fn best_fit(glyph: &BezPath, shape: &BezPath) -> f64 { + let g = signature(glyph).unwrap(); + signatures(shape, true).iter().filter_map(|s| fit(&g, s)).map(|(_, r)| r).fold(f64::INFINITY, f64::min) + } + + #[test] + fn a_contour_started_at_another_corner_still_matches() { + // The counter of letter(), started at its second corner instead of its first. + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((0.0, -700.0)); + p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0)); + p.quad_to((450.0, -300.0), (120.0, -300.0)); + p.line_to((120.0, 0.0)); + p.close_path(); + p.move_to((120.0, -400.0)); + p.quad_to((330.0, -400.0), (330.0, -500.0)); + p.quad_to((330.0, -600.0), (120.0, -600.0)); + p.line_to((120.0, -400.0)); + p.close_path(); + let shape = Affine::translate((40.0, 90.0)) * Affine::rotate(-1.1) * Affine::scale(0.03) * p; + assert_eq!(shape_key(&shape), shape_key(&letter())); + assert!(best_fit(&letter(), &shape) < 1e-6); + // A triangle started at each of its corners. + let tri = |a: (f64, f64), b: (f64, f64), c: (f64, f64)| { + let mut t = BezPath::new(); + t.move_to(a); + t.line_to(b); + t.line_to(c); + t.close_path(); + t + }; + let g = tri((0.0, 0.0), (300.0, 0.0), (0.0, -400.0)); + for s in [tri((300.0, 0.0), (0.0, -400.0), (0.0, 0.0)), tri((0.0, -400.0), (0.0, 0.0), (300.0, 0.0))] { + assert!(best_fit(&g, &s) < 1e-6); + } + } + + #[test] + fn an_edge_split_in_two_reads_as_one() { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((0.0, -350.0)); + p.line_to((0.0, -700.0)); + p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0)); + p.quad_to((450.0, -300.0), (120.0, -300.0)); + p.line_to((120.0, 0.0)); + p.line_to((60.0, 0.0)); + p.close_path(); + p.move_to((120.0, -600.0)); + p.line_to((120.0, -400.0)); + p.quad_to((330.0, -400.0), (330.0, -500.0)); + p.quad_to((330.0, -600.0), (120.0, -600.0)); + p.close_path(); + assert_eq!(shape_key(&p), shape_key(&letter()), "split edges, the closing one too, read as one"); + assert!(best_fit(&letter(), &p) < 1e-6); + } + + #[test] + fn a_detail_between_samples_fails_the_whole_outline_check() { + let bar = |notch: f64| { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((1000.0, 0.0)); + p.line_to((1000.0, -100.0)); + // A notch 2 units wide, in or out, between two samples along the top edge. + p.line_to((501.0, -100.0)); + p.line_to((501.0, -100.0 + notch)); + p.line_to((499.0, -100.0 + notch)); + p.line_to((499.0, -100.0)); + p.line_to((0.0, -100.0)); + p.close_path(); + p + }; + let (out, inn) = (bar(-10.0), bar(10.0)); + assert_eq!(shape_key(&out), shape_key(&inn), "same key"); + let tol = signature(&inn).unwrap().spread * OUTLINE_TOLERANCE; + assert!(!outlines_agree(&out, &inn, tol), "the whole outline does"); + assert!(outlines_agree(&out, &out, tol)); + } + + #[test] + fn readings_that_all_fail_stop_at_the_cap() { + // 48 concentric squares (four tied corners each: 4^48 choices) so large that every reading + // overflows: the tries stop at the cap instead of running through the choices. + let mut p = BezPath::new(); + for i in 1..=48 { + let r = 1e153 * f64::from(i); + p.move_to((-r, -r)); + p.line_to((r, -r)); + p.line_to((r, r)); + p.line_to((-r, r)); + p.close_path(); + } + let t0 = std::time::Instant::now(); + assert!(signatures(&p, true).is_empty()); + assert!(t0.elapsed() < std::time::Duration::from_secs(5), "{:?}", t0.elapsed()); + } + + #[test] + fn the_same_corners_joined_another_way_are_another_outline() { + let poly = |pts: &[(f64, f64)]| { + let mut p = BezPath::new(); + p.move_to(pts[0]); + for q in &pts[1..] { + p.line_to(*q); + } + p.close_path(); + p + }; + let square = poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let bow = poly(&[(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)]); + assert!(!outlines_agree(&square, &bow, 1.0), "every corner lies on the other, the edges do not"); + assert!(outlines_agree(&square, &square, 1.0)); + } +} diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index c9ae809da5..795e2c375b 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -8,7 +8,7 @@ use unicode_bidi::Level; use unicode_script::{Script, UnicodeScript}; use unicode_segmentation::UnicodeSegmentation; -use harfrust::{BufferClusterLevel, Direction, Feature, ShapeOptions, Tag, UnicodeBuffer}; +use harfrust::{Direction, Feature, Tag}; use kurbo::Shape; use skrifa::MetadataProvider; use skrifa::charmap::Charmap; @@ -673,7 +673,7 @@ pub(crate) fn shape_runs( // Split into segments by font coverage (and case, for Small Caps). let mut seg = Segment { db, range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) }; let mut cache: std::collections::HashMap<&str, Arc> = std::collections::HashMap::new(); - let mut script = Script::Common; + let mut boundary = craft_font_catalog::SegmentBoundary::new(primary.id(), level_at(a)); // A grapheme cluster (a letter and its marks, an emoji sequence) is set in one face. for (i, cluster) in text[a..b].grapheme_indices(true) { let i = a + i; @@ -693,20 +693,16 @@ pub(crate) fn shape_runs( }; let small = small_caps && c.is_lowercase(); let next_script = shaping_script(c); - let strong_script = !matches!(next_script, Script::Common | Script::Inherited); - let script_change = strong_script && script != Script::Common && script != next_script; + let strong_script = (!matches!(next_script, Script::Common | Script::Inherited)).then_some(next_script); // Combining marks, zero width joiners and non-joiners, and variation selectors stay // with the character before them. - if (face.id() != seg.face.id() || small != seg.small || level != seg.level || script_change) && !is_mark(c) { + if boundary.advance(face.id(), level, small, strong_script, is_mark(c)) { if i > seg.range.start { seg.range.end = i; shape_segment(text, &range, &seg, feats, out); } seg = Segment { range: i..i, face, small, level, ..seg }; } - if strong_script { - script = next_script; - } } if b > seg.range.start { seg.range.end = b; @@ -1301,10 +1297,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { /// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or /// variation selectors. fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator + '_ { - cluster - .chars() - .map(move |c| digits.map(c)) - .filter(|&c| !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'))) + craft_font_catalog::drawable_characters(cluster, move |c| digits.map(c)) } /// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)? @@ -1316,11 +1309,14 @@ fn in_face(map: Option<&Charmap<'_>>, c: char) -> bool { /// first fallback face with all of them, so that a letter's marks are shaped with it and attach to /// it (#4491); when there is none, the face its first character takes on its own. fn fallback_face(db: &FontDb, primary: &Arc, pmap: Option<&Charmap<'_>>, cluster: &str, digits: Digits) -> Arc { - let fallback = |c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic); - drawn_chars(cluster, digits) - .find_map(|c| fallback(c).filter(|f| drawn_chars(cluster, digits).all(|c| f.covers(c)))) - .or_else(|| drawn_chars(cluster, digits).next().filter(|&c| !in_face(pmap, c)).and_then(fallback)) - .unwrap_or_else(|| primary.clone()) + craft_font_catalog::cluster_face( + cluster, + primary, + |c| digits.map(c), + |c| in_face(pmap, c), + |c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic), + |face, c| face.covers(c), + ) } /// The script `c` is shaped in: Japanese and Chinese text mixes Han, Hiragana, Katakana and @@ -1606,46 +1602,28 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe let along_features = with_more(&|s| feats.resolve(s)); // gid, cluster, x and y advance, x and y offset. let shape = |feats: &[Feature], direction: Direction| { - let mut buf = UnicodeBuffer::new(); - for (i, c) in text_seg.char_indices() { - let cl = (range.start + i) as u32; - let c = st.digits.map(c); - if upper { - for u in c.to_uppercase() { - buf.add(u, cl); - } - } else { - buf.add(c, cl); - } - } - buf.set_direction(direction); - buf.guess_segment_properties(); - if char_level.get() { - buf.set_cluster_level(BufferClusterLevel::Characters); - } - // The characters' language picks the font's forms for it (`locl`: Turkish keeps fi - // apart and the dot on its i). - if let Some(l) = &language { - buf.set_language(l.clone()); - } - // Harfrust keeps this Unicode context for joining/positional shaping, but does not emit - // glyphs for it. This retains context at real style/font segmentation boundaries without - // shaping across those boundaries or claiming cross-style ligatures/mark attachment. - if let Some(pre) = text.get(context.start..range.start) { - buf.set_pre_context(pre); - } - if let Some(post) = text.get(range.end..context.end) { - buf.set_post_context(post); - } - // A buffer whose characters name no script reads as `UNKNOWN`: its plan has none. - let script = Some(buf.script()).filter(|s| *s != harfrust::script::UNKNOWN); - let plan = face.shape_plan(&shaper, buf.direction(), script, language.as_ref(), feats); - let gb = shaper.shape(buf, ShapeOptions::new().features(feats).plan(Some(&plan))); - gb.glyph_infos() - .iter() - .zip(gb.glyph_positions()) - .map(|(info, pos)| (info.glyph_id, info.cluster, pos.x_advance, pos.y_advance, pos.x_offset, pos.y_offset)) - .collect::>() + let input = craft_font_catalog::RunInput { + text: text_seg, + source_start: range.start, + pre_context: text.get(context.start..range.start).unwrap_or_default(), + post_context: text.get(range.end..context.end).unwrap_or_default(), + direction, + language: language.as_ref(), + features: feats, + character_clusters: char_level.get(), + uppercase: upper, + }; + craft_font_catalog::shape_run( + &shaper, + &input, + |c| st.digits.map(c), + |shaper, direction, script, language, features| face.shape_plan(shaper, direction, script, language, features), + ) + // HarfRust clusters are u32; a run beyond that source offset cannot be represented. + .unwrap_or_default() + .into_iter() + .map(|g| (g.glyph_id, g.cluster, g.x_advance, g.y_advance, g.x_offset, g.y_offset)) + .collect::>() }; let along = if level.is_rtl() { Direction::RightToLeft } else { Direction::LeftToRight }; *raw = shape(&along_features, along).into_iter().map(|(g, c, xa, _, xo, yo)| (g, c, xa, xo, yo)).collect(); diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index e397b1f9ed..894e75ed3d 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -4,11 +4,12 @@ //! a click on a circle or arc gives its radius. Escape cancels without leaving any artwork. use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use serde_json::{Value, json}; +use std::collections::HashMap; use vectorcraft_doc::{ - Node, NodeId, + Node, NodeId, NodeKind, dimension::{self, Dimension, DimensionMode, DimensionOptions, DimensionSource, FreePoint, Orientation, PointRef, SegmentRef}, }; -use vectorcraft_geom::{BezPath, Point, Vec2}; +use vectorcraft_geom::{BezPath, Point, Rect, Vec2}; /// The three kinds of dimension the tool draws. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -68,14 +69,22 @@ pub struct DimensionTool { /// Where the next Linear pick lands, as last worked out for the pointer (for the overlays). snapped: Option<(Point, Option)>, /// Whether the last Linear pick worked out landed on the end of a line of a dimension already - /// drawn (shown as an anchor). + /// drawn, or on a corner of a path's preview bounds (shown as an anchor). on_end: bool, + /// The path that holds the last Linear pick worked out, when it landed on a corner of that + /// path's preview bounds. + corner: Option, + /// The path that holds the first Linear point, when it was picked on a corner of that path's + /// preview bounds. + first_corner: Option, /// Whether the press under way began on an anchor a Linear click picks. press_on_anchor: bool, /// The second point clicked for the Linear dimension being placed, and where the pointer was /// for that click (a snap or Shift can move the point away from it): placed with the pointer /// still at either, it is aligned. second: Option<(Point, Point)>, + /// The preview bounds the Linear picks measured, for the document's revision. + preview_boxes: PreviewBoxes, /// While a Linear dimension is placed with its line on the level of another dimension's line: /// the ends of that other line. A Smart Guide runs along the level across both lines. level_guide: Option<(Point, Point)>, @@ -176,9 +185,14 @@ fn anchor_near(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<(usize, /// The anchor nearest `p` within reach, on any editable path (the topmost on a tie), as a link to /// its path. Bounded work, and dimension artwork is skipped, as in [`pick`]. fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> { + anchor_under_where(cx, p, |_| true) +} + +/// [`anchor_under`] outside the objects `keep` turns down, and outside everything in them. +fn anchor_under_where(cx: &ToolContext, p: Point, keep: impl Fn(NodeId) -> bool) -> Option<(Point, PointRef)> { type Best = Option<(f64, Point, PointRef)>; - fn visit(n: &Node, p: Point, reach: f64, budget: &mut usize, best: &mut Best) { - if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() { + fn visit(n: &Node, p: Point, reach: f64, keep: &dyn Fn(NodeId) -> bool, budget: &mut usize, best: &mut Best) { + if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() || !keep(n.id) { return; } if let Some(path) = n.path_data() { @@ -197,17 +211,178 @@ fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> { } if let Some(ch) = n.children() { for c in ch.iter().rev() { - visit(c, p, reach, budget, best); + visit(c, p, reach, keep, budget, best); } } } let (reach, mut budget, mut best) = (cx.tol(ANCHOR_REACH), 20_000usize, None); for n in cx.doc.layers.iter().rev() { - visit(n, p, reach, &mut budget, &mut best); + visit(n, p, reach, &keep, &mut budget, &mut best); } best.map(|(_, at, r)| (at, r)) } +/// The geometric bounds of the paths [`preview_corner`] looked at, and the preview bounds of +/// those it measured, kept while the document is unchanged, so that the pointer moving over the +/// art measures each path once. +#[derive(Default)] +struct PreviewBoxes { + revision: Option<(u64, u64)>, + geometric: HashMap>, + preview: HashMap>, + /// Whether a point at each corner (by object and corner number) can be held against its path. + holdable: HashMap<(NodeId, usize), bool>, +} + +/// A corner of an object's preview bounds that a Linear pick can land on. +#[derive(Clone, Copy, Debug)] +struct PreviewCorner { + at: Point, + /// The path the point is held against. + holder: NodeId, + /// The same corner of the object's geometric bounds: an anchor of `holder` there is the + /// anchor the corner stands in for. + stands_for: Point, +} + +/// With Use Preview Bounds on, the corner of a path's or compound path's preview bounds (its +/// strokes and effects included) nearest `p` within reach, on any editable one whose preview +/// bounds differ from its geometric bounds. In a compound path, the member whose own box reaches +/// nearest to the corner holds it. The work is bounded, and dimension artwork is skipped, as in +/// [`pick`]. `cache` keeps the bounds measured for the document's revision. +fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Option { + struct Walk<'a, 'c> { + symbols: Option>, + doc: &'a vectorcraft_doc::Document, + cache: &'c mut PreviewBoxes, + p: Point, + reach: f64, + budget: usize, + best: Option<(f64, PreviewCorner)>, + } + fn visit(n: &Node, w: &mut Walk) { + if w.budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() { + return; + } + w.budget -= 1; + // Only effects, on the object or on one of its fills or strokes, paint further out than + // its strokes reach. + let effects = !n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()); + let reach = n.appearance.outset() + w.reach; + let corners = |r: Rect| [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + // A path is its own member; a compound path's members are its paths. + let compound = match &n.kind { + NodeKind::Compound { children, .. } => Some(children.as_slice()), + _ => None, + }; + let members = + || compound.into_iter().flatten().map(|c| c.as_ref()).chain(compound.is_none().then_some(n)).filter(|m| m.path_data().is_some()); + // A path made into a guide draws as a guide, without its strokes or effects. The pointer + // test includes the right and bottom edges, as the distance test below does. + let within = |r: Rect| (r.x0..=r.x1).contains(&w.p.x) && (r.y0..=r.y1).contains(&w.p.y); + if !n.is_guide() + && members().next().is_some() + && let Some(geometric) = *w.cache.geometric.entry(n.id).or_insert_with(|| n.geometric_bounds()) + && (effects || within(geometric.inflate(reach, reach))) + { + let doc = w.doc; + let measured = match w.cache.preview.get(&n.id) { + Some(r) => *r, + None => { + let symbols = w.symbols.get_or_insert_with(|| doc.symbol_boxes()); + let r = vectorcraft_effects::preview::visual_bounds(symbols, n); + w.cache.preview.insert(n.id, r); + r + } + }; + if let Some(r) = measured + && r != geometric + { + for (k, q) in corners(r).into_iter().enumerate() { + let d = q.distance(w.p); + if d > w.reach || w.best.is_some_and(|(nearest, ..)| d >= nearest) { + continue; + } + // The path whose own box reaches furthest towards the corner holds it: in a + // compound path, the member that puts that corner where it is. A hidden or + // locked member gives no corner. + let mut holder: Option<(f64, NodeId, bool)> = None; + for m in members() { + let Some(b) = *w.cache.geometric.entry(m.id).or_insert_with(|| m.geometric_bounds()) else { continue }; + let gap = corners(b).get(k).map_or(f64::INFINITY, |c| c.distance(q)); + let editable = m.visible && !m.locked; + if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) { + holder = Some((gap, m.id, editable)); + } + } + let holder = holder.filter(|(.., editable)| *editable).map(|(gap, id, _)| (gap, id)); + // A path that cannot hold a point at the corner (a stroked dot, whose anchors + // all coincide) gives no corner. + let holdable = |id: NodeId, cache: &mut PreviewBoxes| { + *cache.holdable.entry((n.id, k)).or_insert_with(|| FreePoint::on(doc, id, q).is_some()) + }; + let holder = holder.filter(|(_, id)| holdable(*id, w.cache)); + if let Some(((_, holder), stands_for)) = holder.zip(corners(geometric).get(k).copied()) { + w.best = Some((d, PreviewCorner { at: q, holder, stands_for })); + } + } + } + } + // A compound path draws its members with its own appearance: they give no corners of + // their own. + if compound.is_none() + && let Some(ch) = n.children() + { + for c in ch.iter().rev() { + visit(c, w); + } + } + } + // Anchors take a pick whatever the snapping options, and so do the corners standing in for them. + if !cx.preview_bounds { + return None; + } + if cache.revision != Some(cx.revision) { + *cache = PreviewBoxes { revision: Some(cx.revision), ..Default::default() }; + } + let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, best: None }; + for n in cx.doc.layers.iter().rev() { + visit(n, &mut w); + } + w.best.map(|(_, corner)| corner) +} + +/// The anchor a pick at `p` lands on instead of `corner`, given `anchor`, the nearest anchor +/// within reach; `None` when the corner takes it (VectorCraft's own rule). The corner takes the +/// pick from the anchors of the path holding it at the same corner of the object's geometric +/// bounds, which sit on the stroke's centerline. An anchor right on the corner takes it, and so +/// does the nearest other anchor, of this object or of other art, when it is nearer the pointer +/// than the corner. The holder's anchors and the other art are searched with a budget each, and +/// `anchor` wins a tie, as the topmost. +fn anchor_over_corner(cx: &ToolContext, p: Point, corner: &PreviewCorner, anchor: Option<(Point, PointRef)>) -> Option<(Point, PointRef)> { + if anchor.as_ref().is_some_and(|(at, _)| at.distance(corner.at) <= 1e-9) { + return anchor; + } + let stands_in = |(at, nearest): &(Point, PointRef)| nearest.node == corner.holder && at.distance(corner.stands_for) <= 1e-9; + let first = anchor.filter(|a| !stands_in(a)); + let reach = cx.tol(ANCHOR_REACH); + let own = cx.doc.node(corner.holder).and_then(|n| n.path_data()).and_then(|path| { + let anchors = path.subpaths.iter().enumerate().flat_map(|(subpath, sp)| sp.anchors.iter().enumerate().map(move |(i, a)| (subpath, i, a.p))); + anchors + .take(20_000) + .filter(|(.., q)| q.distance(p) <= reach && q.distance(corner.stands_for) > 1e-9) + .min_by(|(.., a), (.., b)| a.distance(p).total_cmp(&b.distance(p))) + .map(|(subpath, anchor, q)| (q, PointRef { node: corner.holder, subpath, anchor })) + }); + let other = anchor_under_where(cx, p, |id| id != corner.holder); + first + .into_iter() + .chain(other) + .chain(own) + .filter(|(q, _)| q.distance(p) < corner.at.distance(p) || q.distance(corner.at) <= 1e-9) + .min_by(|(a, _), (b, _)| a.distance(p).total_cmp(&b.distance(p))) +} + /// Where a pick at `p` lands on the artwork of the visible, unlocked dimensions already drawn, /// with no link to it: the nearest end of one of their lines (dimension and extension lines) /// within the anchor reach, as an anchor (`true`); else the nearest point of one of those lines @@ -361,10 +536,23 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { /// A point on a segment keeps its place along the segment. Any other point is held /// against the anchors of the path under it, or, with no path under it, the path of the other /// point, so that it moves with that path. None when neither point has a path to link to. -fn points_source(cx: &ToolContext, (a, ra): (Point, &Option), (b, rb): (Point, &Option)) -> Option { - let (edge_a, edge_b) = (pick(cx, a), pick(cx, b)); - let node = |r: &Option, e: &Option| r.as_ref().map(|r| r.node).or_else(|| e.as_ref().map(|e| e.node)); - let (path_a, path_b) = (node(ra, &edge_a), node(rb, &edge_b)); +/// `held_a` and `held_b` name the path holding a point picked on a corner of that path's +/// preview bounds: such a point is held against that path, however far its strokes or effects +/// put the corner from the path and whatever other segment lies there. +fn points_source( + cx: &ToolContext, + (a, ra, held_a): (Point, &Option, Option), + (b, rb, held_b): (Point, &Option, Option), +) -> Option { + // A path deleted since the pick holds nothing. + let holder = |held: Option| held.filter(|node| cx.doc.node(*node).is_some()); + let (corner_a, corner_b) = (holder(held_a), holder(held_b)); + let edge = |p: Point, corner: Option| if corner.is_some() { None } else { pick(cx, p) }; + let (edge_a, edge_b) = (edge(a, corner_a), edge(b, corner_b)); + let node = |r: &Option, corner: Option, e: &Option| { + r.as_ref().map(|r| r.node).or(corner).or_else(|| e.as_ref().map(|e| e.node)) + }; + let (path_a, path_b) = (node(ra, corner_a, &edge_a), node(rb, corner_b, &edge_b)); let free = |p: Point, r: &Option, edge: &Option, own: Option, other: Option| { if r.is_some() { return None; @@ -382,7 +570,10 @@ fn points_source(cx: &ToolContext, (a, ra): (Point, &Option), (b, rb): } impl DimensionTool { - /// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as + /// Where a Linear pick at `p` lands: with Use Preview Bounds on, on the nearest corner of a + /// path's preview bounds within reach, where they differ from its anchors, unless another + /// anchor is nearer (held against the path, labeled "anchor"; [`anchor_over_corner`]); else on the + /// nearest anchor of any path, within reach (kept as /// a link to its path), labeled "anchor"; else on the nearest end of a line of a dimension /// already drawn, within the same reach (no link), also labeled "anchor"; else where Smart Guides put it (another object's anchor or centre, in /// line with one, or for the second point square to a segment or grazing a curve from the @@ -399,7 +590,18 @@ impl DimensionTool { }); let guided = self.snap.hover(cx, p, &[], leave.as_ref()); self.on_end = false; - if let Some((point, reference)) = anchor_under(cx, p) { + self.corner = None; + let mut anchor = anchor_under(cx, p); + if let Some(corner) = preview_corner(cx, p, &mut self.preview_boxes) { + anchor = anchor_over_corner(cx, p, &corner, anchor); + if anchor.is_none() { + self.on_end = true; + self.corner = Some(corner.holder); + self.snap.label(corner.at, "anchor"); + return (corner.at, None); + } + } + if let Some((point, reference)) = anchor { self.snap.label(point, "anchor"); return (point, Some(reference)); } @@ -555,6 +757,8 @@ impl DimensionTool { self.press = None; self.press_on_anchor = false; self.on_end = false; + self.corner = None; + self.first_corner = None; self.points.clear(); self.lines.clear(); self.dragging = false; @@ -570,15 +774,22 @@ impl DimensionTool { match self.kind { Kind::Linear => { let (mut at, mut reference) = self.snap_linear(cx, p); + let mut corner = self.corner; if mods.shift && let Some((last, _)) = self.points.last() { + let snapped = at; at = constrained(cx, *last, at); reference = reference.filter(|r| r.position(cx.doc) == Some(at)); + corner = corner.filter(|_| at.distance(snapped) <= 1e-9); } self.points.push((at, reference)); + if self.points.len() == 1 { + self.first_corner = corner; + } if let [(a, ra), (b, rb)] = self.points.as_slice() { - let source = points_source(cx, (*a, ra), (*b, rb)); + let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner)); + self.first_corner = None; let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source); if d.resolve(cx.doc).is_ok() { self.second = Some((*b, p)); @@ -678,11 +889,14 @@ impl Tool for DimensionTool { self.press = Some((ev.pos, None)); return self.preview(cx, ev.pos); } - // A Linear press on an anchor, or on the end of a dimension's line, picks it unless - // it drags past the anchor's reach: moving a few pixels before the release does not - // drag out the dimension of a segment under the pointer. - self.press_on_anchor = - self.kind == Kind::Linear && (anchor_under(cx, ev.pos).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); + // A Linear press on an anchor, on a corner of preview bounds or on the end of a + // dimension's line, picks it unless it drags past the anchor's reach: moving a few + // pixels before the release does not drag out the dimension of a segment under the + // pointer. + self.press_on_anchor = self.kind == Kind::Linear + && (anchor_under(cx, ev.pos).is_some() + || preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some() + || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); self.press = Some((ev.pos, self.target(cx, ev.pos))); vec![] } @@ -797,7 +1011,7 @@ impl Tool for DimensionTool { let linear_pick = self.kind == Kind::Linear && self.pending.is_none() && self.lines.is_empty(); let snapped = self.snapped.clone().filter(|_| linear_pick); if let Some((q, reference)) = &snapped - && (reference.is_some() || q.distance(self.at) > 1e-9) + && (reference.is_some() || self.on_end || q.distance(self.at) > 1e-9) { let on_anchor = reference.is_some() || self.on_end; out.push(Overlay::Anchor { p: *q, color, filled: !on_anchor, size: if on_anchor { 10.0 } else { 6.0 } }); @@ -1037,6 +1251,347 @@ mod tests { assert!(at.distance(pending.b) < 1e-9, "{at:?} {:?}", pending.b); } + /// With Use Preview Bounds on, clicks by the corners of a stroked path land on the corners of + /// its preview bounds, held against the path, so the dimension measures the outside of the + /// stroke as W and H do. Without a stroke, or with the preference off, the anchors are picked. + #[test] + fn with_preview_bounds_points_land_on_the_corners_of_the_stroke() { + use vectorcraft_doc::dimension::FreePoint; + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let pick = |c: &ToolContext| { + let mut t = DimensionTool::default(); + for (x, y) in [(101.0, 101.0), (199.0, 199.0)] { + t.pointer(c, &PointerEvent::new(PointerKind::Move, x, y)); + t.pointer(c, &PointerEvent::new(PointerKind::Down, x, y)); + t.pointer(c, &PointerEvent::new(PointerKind::Up, x, y)); + } + t.pending.expect("both points were picked") + }; + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let pending = pick(&c); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { a: None, b: None, free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + for (free, at) in [(free_a, pending.a), (free_b, pending.b)] { + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{free:?}"); + assert!(free.position(&d).expect("the anchors that hold it exist").distance(at) < 1e-9); + } + // A line of another path through the corner leaves the point held against the rectangle. + let mut crossed = d.clone(); + let (l, line) = (crossed.layers[0].id, crossed.alloc_id()); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 99.5), Point::new(300.0, 99.5)], false)); + crossed.insert(Some(l), 1, Node::path(line, path, vectorcraft_doc::Appearance::default_art())).expect("the line"); + let pending = pick(&ToolContext { preview_bounds: true, ..cx(&crossed, &s, &p) }); + assert!(near(pending.a, Point::new(99.5, 99.5)), "{:?}", pending.a); + let Some(DimensionSource::Points { free_a: Some(free_a), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(matches!(free_a, FreePoint::Anchors { node, .. } if *node == id), "{free_a:?}"); + let anchors = |pending: &Dimension| (pending.a, pending.b, pending.source.clone()); + let anchor = |anchor| Some(PointRef { node: id, subpath: 0, anchor }); + let linked = DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None, free_a: None, free_b: None }; + let off = pick(&cx(&d, &s, &p)); + assert_eq!(anchors(&off), (Point::new(100.0, 100.0), Point::new(200.0, 200.0), Some(linked.clone())), "preference off"); + let mut bare = d.clone(); + bare.node_mut(id).expect("the rectangle").appearance = vectorcraft_doc::Appearance::default().into(); + let c = ToolContext { preview_bounds: true, ..cx(&bare, &s, &p) }; + assert_eq!(anchors(&pick(&c)), (Point::new(100.0, 100.0), Point::new(200.0, 200.0), Some(linked)), "no stroke"); + // A compound path's stroke: the points are held against the member that reaches the + // corner, not the small hole drawn first. + let mut compound = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, hole, part, whole) = (compound.layers[0].id, compound.alloc_id(), compound.alloc_id(), compound.alloc_id()); + let square = |id, a: f64, b: f64| { + std::sync::Arc::new(Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(a, a, b, b)), Default::default())) + }; + let children = vec![square(hole, 140.0, 160.0), square(part, 100.0, 200.0)]; + let mut n = Node::new(whole, NodeKind::Compound { children, rule: Default::default() }); + n.appearance = vectorcraft_doc::Appearance::default_art().into(); + compound.insert(Some(l), 0, n).expect("the compound path"); + let pending = pick(&ToolContext { preview_bounds: true, ..cx(&compound, &s, &p) }); + assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + for free in [free_a, free_b] { + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == part), "{free:?}"); + } + // A 40 point stroke, and an Offset Path effect on the fill, put the corners further from + // the path than a click on the path reaches: the points still land there and stay linked. + let mut wide = vectorcraft_doc::Appearance::default_art(); + wide.stroke_mut().expect("a stroke").width = 40.0; + let mut offset = vectorcraft_doc::Appearance::default_art(); + let effect = + vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 30, "joins": "miter"}), visible: true }; + offset.effects_mut(Some(0)).expect("the fill").push(effect); + for (appearance, out) in [(wide, 20.0), (offset, 30.0)] { + let mut d = d.clone(); + d.node_mut(id).expect("the rectangle").appearance = appearance.into(); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + for (x, y) in [(101.0 - out, 101.0 - out), (199.0 + out, 199.0 + out)] { + t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y)); + } + let pending = t.pending.expect("both points were picked"); + let (a, b) = (Point::new(100.0 - out, 100.0 - out), Point::new(200.0 + out, 200.0 + out)); + assert!(near(pending.a, a) && near(pending.b, b), "{out}: {:?} {:?}", pending.a, pending.b); + let Some(DimensionSource::Points { free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else { + panic!("{out}: {:?}", pending.source) + }; + for free in [free_a, free_b] { + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{out}: {free:?}"); + } + } + // A press on a corner over another path's segment picks the corner when the pointer moves + // a few pixels before the release, as on an anchor. + let mut d = d.clone(); + let mut wide = vectorcraft_doc::Appearance::default_art(); + wide.stroke_mut().expect("a stroke").width = 40.0; + d.node_mut(id).expect("the rectangle").appearance = wide.into(); + let (l, line) = (d.layers[0].id, d.alloc_id()); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 82.0), Point::new(95.0, 82.0)], false)); + d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line"); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 81.0, 81.0)).is_empty()); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 85.0, 81.0)).is_empty(), "no segment dimension is dragged out"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 85.0, 81.0)).is_empty()); + assert!(t.points.first().is_some_and(|(q, _)| near(*q, Point::new(80.0, 80.0))), "{:?}", t.points); + } + + /// With Use Preview Bounds on, hovering by a corner of a stroked path's preview bounds, or + /// right on it, shows the anchor ring there. + #[test] + fn hovering_a_corner_of_the_preview_bounds_shows_the_anchor_ring() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + for (x, y) in [(101.0, 101.0), (99.5, 99.5)] { + let mut t = DimensionTool::default(); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y)); + let ring = t + .overlays(&c) + .into_iter() + .any(|o| matches!(o, Overlay::Anchor { p, filled: false, size, .. } if p.distance(Point::new(99.5, 99.5)) < 1e-9 && size == 10.0)); + assert!(ring, "({x}, {y})"); + let label = t + .snap + .guides() + .iter() + .any(|o| matches!(o, Overlay::Label { p, text, .. } if text == "anchor" && p.distance(Point::new(99.5, 99.5)) < 1e-9)); + assert!(label, "({x}, {y}): {:?}", t.snap.guides()); + } + } + + /// With Use Preview Bounds on, a corner of the preview bounds takes a pick with Smart Guides and + /// Snap to Point off, as an anchor does, and an anchor of other art nearer the pointer than the + /// corner takes it from the corner. The point moves with the path, and a later change to the + /// stroke weight leaves it where it was. + #[test] + fn preview_bounds_corners_take_picks_as_anchors_do() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + let pick = |c: &ToolContext, at: [(f64, f64); 2]| { + let mut t = DimensionTool::default(); + for (x, y) in at { + t.pointer(c, &PointerEvent::new(PointerKind::Move, x, y)); + t.pointer(c, &PointerEvent::new(PointerKind::Down, x, y)); + t.pointer(c, &PointerEvent::new(PointerKind::Up, x, y)); + } + t.pending.expect("both points were picked") + }; + let unsnapped = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; + let pending = pick(&unsnapped, [(101.0, 101.0), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b); + // An unstroked line whose end lies 2.5 points outside the corner. + let mut other = d.clone(); + let (l, line) = (other.layers[0].id, other.alloc_id()); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(97.0, 97.0), Point::new(50.0, 50.0)], false)); + other.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line"); + let c = ToolContext { preview_bounds: true, ..cx(&other, &s, &p) }; + let pending = pick(&c, [(97.5, 97.5), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(97.0, 97.0)), "the line's end is nearer: {:?}", pending.a); + let Some(DimensionSource::Points { a: Some(a), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert_eq!(a.node, line); + let pending = pick(&c, [(99.0, 99.0), (199.0, 199.0)]); + assert!(near(pending.a, Point::new(99.5, 99.5)), "the corner is nearer: {:?}", pending.a); + // Right on the rectangle's anchor, with another path's anchor nearer than the corner: that + // anchor takes the point, not the rectangle's own anchor on the stroke's centerline. + let mut beside = d.clone(); + let (l, line) = (beside.layers[0].id, beside.alloc_id()); + let path = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(100.5, 100.0), Point::new(150.0, 50.0)], false)); + beside.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line"); + let pending = pick(&ToolContext { preview_bounds: true, ..cx(&beside, &s, &p) }, [(100.0, 100.0), (199.0, 199.0)]); + let Some(DimensionSource::Points { a: Some(a), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(near(pending.a, Point::new(100.5, 100.0)) && a.node == line, "{:?} {a:?}", pending.a); + // The point held against the rectangle moves with it and stays put when the stroke changes. + let pending = pick(&ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }, [(101.0, 101.0), (199.0, 199.0)]); + let Some(DimensionSource::Points { free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + let mut moved = d.clone(); + moved.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::translate((10.0, 0.0)), false); + assert!(free.position(&moved).is_some_and(|q| near(q, Point::new(109.5, 99.5))), "{:?}", free.position(&moved)); + let mut wider = d.clone(); + let mut wide = vectorcraft_doc::Appearance::default_art(); + wide.stroke_mut().expect("a stroke").width = 40.0; + wider.node_mut(id).expect("the rectangle").appearance = wide.into(); + assert!(free.position(&wider).is_some_and(|q| near(q, Point::new(99.5, 99.5))), "{:?}", free.position(&wider)); + // Scaled 200% with Scale Strokes off, the point moves with the anchors and no longer sits + // on the corner of the preview bounds, which the 1 point stroke puts at (199.5, 199.5). + let mut scaled = d.clone(); + scaled.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::scale(2.0), false); + assert!(free.position(&scaled).is_some_and(|q| near(q, Point::new(199.0, 199.0))), "{:?}", free.position(&scaled)); + } + + /// With Use Preview Bounds on, a corner takes the pick only from the anchors at the same corner + /// of its object's geometric bounds. The other anchors of a small stroked circle stay + /// pickable, so does the end of another line lying on the anchor the corner stands in for, and + /// of two stroked rectangles sharing an edge, each corner of the shared anchors is held against + /// its own rectangle. + #[test] + fn a_corner_takes_only_the_anchor_it_stands_for() { + let (s, p) = (Selection::default(), paint()); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, circle) = (d.layers[0].id, d.alloc_id()); + let path = vectorcraft_geom::shapes::ellipse(Rect::new(296.0, 296.0, 304.0, 304.0)); + d.insert(Some(l), 0, Node::path(circle, path, vectorcraft_doc::Appearance::default_art())).expect("the circle"); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + let (q, reference) = t.snap_linear(&c, Point::new(300.0, 296.0)); + assert!(near(q, Point::new(300.0, 296.0)) && reference.is_some_and(|r| r.node == circle), "{q:?}"); + let (q, reference) = t.snap_linear(&c, Point::new(296.5, 296.5)); + assert!(near(q, Point::new(295.5, 295.5)) && reference.is_none() && t.corner == Some(circle), "{q:?}"); + // An unstroked line ending right on the rectangle's anchor: a click there picks the line's + // end, and a click nearer the corner picks the corner. + let (mut d, id) = doc_with_rect(); + let (l, line) = (d.layers[0].id, d.alloc_id()); + let path = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 100.0), Point::new(50.0, 20.0)], false)); + d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line"); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + let (q, reference) = t.snap_linear(&c, Point::new(100.0, 100.0)); + assert!(near(q, Point::new(100.0, 100.0)) && reference.is_some_and(|r| r.node == line), "{q:?}"); + let (q, reference) = t.snap_linear(&c, Point::new(99.6, 99.6)); + assert!(near(q, Point::new(99.5, 99.5)) && reference.is_none() && t.corner == Some(id), "{q:?}"); + // Another path's end right on the corner: a click on the rectangle's anchor picks that end. + let (mut d, _) = doc_with_rect(); + let (l, line) = (d.layers[0].id, d.alloc_id()); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(99.5, 99.5), Point::new(50.0, 20.0)], false)); + d.insert(Some(l), 0, Node::path(line, path, Default::default())).expect("the line"); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + let (q, reference) = t.snap_linear(&c, Point::new(100.0, 100.0)); + assert!(near(q, Point::new(99.5, 99.5)) && reference.as_ref().is_some_and(|r| r.node == line), "{q:?} {reference:?}"); + // A stroked dot, a path whose two anchors coincide, cannot hold a point at a corner: a + // click by it picks its anchor. + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, dot) = (d.layers[0].id, d.alloc_id()); + let path = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(300.0, 300.0), Point::new(300.0, 300.0)], false)); + let mut round = vectorcraft_doc::Appearance::default_art(); + let stroke = round.stroke_mut().expect("a stroke"); + (stroke.width, stroke.cap) = (10.0, vectorcraft_doc::LineCap::Round); + d.insert(Some(l), 0, Node::path(dot, path, round)).expect("the dot"); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + let (q, reference) = t.snap_linear(&c, Point::new(296.0, 296.0)); + assert!(near(q, Point::new(300.0, 300.0)) && reference.is_some_and(|r| r.node == dot) && t.corner.is_none(), "{q:?}"); + // A stroked rectangle made into a guide, and a stroked member of a compound path without + // a stroke of its own, give no corners. + for kind in ["guide", "member"] { + let (mut d, id) = doc_with_rect(); + let mut wide = vectorcraft_doc::Appearance::default_art(); + wide.stroke_mut().expect("a stroke").width = 40.0; + if kind == "guide" { + let n = d.node_mut(id).expect("the rectangle"); + n.appearance = wide.into(); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + } else { + let mut fresh = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, part, whole) = (fresh.layers[0].id, fresh.alloc_id(), fresh.alloc_id()); + let mut member = Node::path(part, vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), Default::default()); + member.appearance = wide.into(); + let n = Node::new(whole, NodeKind::Compound { children: vec![std::sync::Arc::new(member)], rule: Default::default() }); + fresh.insert(Some(l), 0, n).expect("the compound path"); + d = fresh; + } + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + let (q, _) = t.snap_linear(&c, Point::new(81.0, 81.0)); + assert!(!near(q, Point::new(80.0, 80.0)) && t.corner.is_none(), "{kind}: {q:?}"); + } + // Two stroked rectangles sharing the edge x = 200; the right one is on top. + let (mut d, left) = doc_with_rect(); + let (l, right) = (d.layers[0].id, d.alloc_id()); + let path = vectorcraft_geom::shapes::rectangle(Rect::new(200.0, 100.0, 300.0, 200.0)); + d.insert(Some(l), 1, Node::path(right, path, vectorcraft_doc::Appearance::default_art())).expect("the right rectangle"); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + for (pointer, corner, holder) in [((200.4, 99.6), (200.5, 99.5), left), ((199.6, 99.6), (199.5, 99.5), right)] { + let mut t = DimensionTool::default(); + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + t.pointer(&c, &PointerEvent::new(kind, pointer.0, pointer.1)); + } + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + t.pointer(&c, &PointerEvent::new(kind, 250.0, 300.0)); + } + let pending = t.pending.expect("both points were picked"); + assert!(near(pending.a, Point::new(corner.0, corner.1)), "{pointer:?}: {:?}", pending.a); + let Some(DimensionSource::Points { a: None, free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == holder), "{pointer:?}: {free:?}"); + } + } + + /// A point is held against a path for a corner of its preview bounds only when it was picked + /// there: the same position picked another way links to the segment under it. + #[test] + fn a_point_is_held_for_a_corner_only_when_picked_on_it() { + let (mut d, id) = doc_with_rect(); + let (l, line) = (d.layers[0].id, d.alloc_id()); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 99.5), Point::new(300.0, 99.5)], false)); + d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line"); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let (corner, b) = (Point::new(99.5, 99.5), Point::new(250.0, 99.5)); + for (held, node) in [(Some(id), id), (None, line)] { + let source = points_source(&c, (corner, &None, held), (b, &None, None)); + let Some(DimensionSource::Points { free_a: Some(free), .. }) = &source else { panic!("{source:?}") }; + let linked = match free { + FreePoint::Anchors { node, .. } => *node, + FreePoint::OnSegment { edge, .. } => edge.node, + }; + assert_eq!(linked, node, "{held:?}: {free:?}"); + } + } + + /// Hovering right on the end of a dimension's line shows the anchor ring there. + #[test] + fn hovering_right_on_a_dimension_lines_end_shows_the_anchor_ring() { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let path = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(300.0, 300.0), Point::new(400.0, 300.0)], false)); + let mut n = Node::path(id, path, Default::default()); + let recipe = DimensionTool::default().recipe(DimensionMode::Linear, Point::new(0.0, 0.0), Point::new(50.0, 0.0), Point::ZERO, None); + n.extras_mut().dimension = Some(Box::new(recipe)); + d.insert(Some(l), 0, n).expect("the dimension's line"); + let (s, p) = (Selection::default(), paint()); + let c = ToolContext { smart_guides: true, snap_to_point: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 300.0, 300.0)); + let ring = t + .overlays(&c) + .into_iter() + .any(|o| matches!(o, Overlay::Anchor { p, filled: false, size, .. } if p.distance(Point::new(300.0, 300.0)) < 1e-9 && size == 10.0)); + assert!(ring, "{:?}", t.overlays(&c)); + } + /// The anchors of a live rectangle are picked the same way. #[test] fn a_press_on_a_live_shapes_anchor_picks_it() { diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 3389746f2d..93d2595016 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -4,7 +4,8 @@ //! Delete: click an anchor to remove it, re-fitting the neighbouring curve (Alt = add). //! Anchor Point: click a smooth anchor → corner; drag an anchor → pull out smooth handles; click a //! handle end → retract that handle only (#2267); drag a handle → move it independently (Shift: at -//! 45° steps round its anchor); drag a segment → reshape the curve, a selected blend's spine's too, +//! 45° steps round its anchor; Alt: link it with the opposite handle, the anchor made smooth, except +//! when the Pen lends the tool); drag a segment → reshape the curve, a selected blend's spine's too, //! straight or curved (#1111; Shift: its handles at right angles to the line between its anchors, //! at one length). Shift held at the press on an anchor moves it instead, handles and all (Shift //! still held: at 45° steps from where it was). Space held during a convert- or handle-drag moves @@ -103,6 +104,9 @@ pub struct AnchorTool { measure: Option<(Point, f64, f64)>, /// While Space is held during a convert/handle drag, the shape gesture to return to. space_resume: Option, + /// Lent by the Pen for its Alt gestures: Alt-dragging a handle moves it independently, as + /// without Alt, instead of linking it with the opposite handle. + lent: bool, } impl AnchorTool { @@ -113,7 +117,20 @@ impl AnchorTool { "scissors" => "scissors", _ => "addAnchor", }; - Self { id, state: State::Idle, guides: vec![], snap: HandleSnap::default(), measure: None, space_resume: None } + Self { id, state: State::Idle, guides: vec![], snap: HandleSnap::default(), measure: None, space_resume: None, lent: false } + } + + /// The Anchor Point tool as the Pen lends it with Alt held: an Alt-drag on a handle moves only + /// that handle. + pub(crate) fn lent_by_pen() -> Self { + Self { lent: true, ..Self::new("anchorPoint") } + } + + /// The handle-drag params: Alt held on the chosen Anchor Point tool links the handle with the + /// opposite one, making the anchor smooth; otherwise the handle moves independently. + fn handle_mode(&self, mut params: serde_json::Value, alt: bool) -> serde_json::Value { + params[if alt && !self.lent { "link" } else { "independent" }] = json!(true); + params } fn anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option { @@ -458,7 +475,10 @@ impl Tool for AnchorTool { }; Action::Preview( "object.blend.spine.moveAnchor".into(), - json!({"id": id.0, "anchor": ai, "handle": if out { "out" } else { "in" }, "x": q.x, "y": q.y, "independent": true}), + self.handle_mode( + json!({"id": id.0, "anchor": ai, "handle": if out { "out" } else { "in" }, "x": q.x, "y": q.y}), + ev.mods.alt, + ), ) } State::Handle { id, si, ai, out, .. } => { @@ -466,7 +486,10 @@ impl Tool for AnchorTool { self.guides = guides; Action::Preview( "path.setHandle".into(), - json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" }, "x": q.x, "y": q.y, "independent": true}), + self.handle_mode( + json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" }, "x": q.x, "y": q.y}), + ev.mods.alt, + ), ) } State::Reshape { id, seg, t, start, spine: true, .. } => Action::Preview( diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index 903ae5bea8..4e4af7f997 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -610,3 +610,88 @@ fn anchor_point_shift_drag_honors_measurement_labels() { assert!(t.overlays(&on).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &want))); assert!(!t.overlays(&off).iter().any(|o| matches!(o, Overlay::Measure { .. }))); } + +/// Alt held while dragging a handle links it with the opposite handle (`link`), making the +/// anchor smooth; without Alt the handle moves on its own. Shift with Alt keeps the 45° steps, an +/// Alt-click still retracts the handle, and Escape cancels the linking drag. The Pen, lending the +/// tool for its Alt gestures, keeps moving the handle on its own. +#[test] +fn anchor_point_alt_drag_links_a_handle_with_the_opposite_one() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(300.0, 300.0)], false); + // A corner: handles at (240, 320) and (170, 320), not in line. + sp.anchors[1] = Anchor::with_handles(Point::new(200.0, 300.0), Point::new(170.0, 320.0), Point::new(240.0, 320.0)); + let path = vectorcraft_geom::PathData::single(sp); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let drag = |t: &mut AnchorTool, mods: Mods, x: f64, y: f64| { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 240.0, 320.0).with_mods(mods)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y).with_mods(mods)) + }; + let set = |x: f64, y: f64, key: &str| { + let mut params = json!({"id": id.0, "subpath": 0, "anchor": 1, "which": "out", "x": x, "y": y}); + params[key] = json!(true); + Action::Preview("path.setHandle".into(), params) + }; + + let mut t = AnchorTool::new("anchorPoint"); + assert_eq!(drag(&mut t, alt, 250.0, 340.0), vec![Action::Begin("Reshape".into()), set(250.0, 340.0, "link")]); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 340.0).with_mods(alt)), vec![Action::Commit]); + // Without Alt the handle moves on its own, as before. + assert_eq!(drag(&mut t, Mods::default(), 250.0, 340.0), vec![Action::Begin("Reshape".into()), set(250.0, 340.0, "independent")]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 340.0)); + + // Shift with Alt: the linked handle stays at 45° steps round its anchor. + let shift_alt = Mods { shift: true, alt: true, ..Mods::default() }; + let a = drag(&mut t, shift_alt, 250.0, 345.0); + let Some(Action::Preview(c, args)) = a.get(1) else { panic!("{a:?}") }; + assert_eq!((c.as_str(), &args["link"], args.get("independent")), ("path.setHandle", &json!(true), None)); + let (dx, dy) = (args["x"].as_f64().unwrap_or(f64::NAN) - 200.0, args["y"].as_f64().unwrap_or(f64::NAN) - 300.0); + assert!(dx > 0.0 && (dx - dy).abs() < 1e-6, "{args}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 345.0)); + + // An Alt-click on the handle retracts it, as a click without Alt does. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 240.0, 320.0).with_mods(alt)); + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 240.0, 320.0).with_mods(alt)), + vec![Action::Exec( + "path.setHandle".into(), + json!({"id": id.0, "subpath": 0, "anchor": 1, "which": "out", "x": 200.0, "y": 300.0, "independent": true}) + )] + ); + + // Escape cancels the linking drag; its release does nothing. + drag(&mut t, alt, 250.0, 340.0); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 340.0).with_mods(alt)).is_empty()); + + // Lent by the Pen, Alt-drag moves the handle on its own. + let mut lent = AnchorTool::lent_by_pen(); + assert_eq!(drag(&mut lent, alt, 250.0, 340.0), vec![Action::Begin("Reshape".into()), set(250.0, 340.0, "independent")]); +} + +/// Alt-dragging a selected blend's spine handle links it with the opposite one. +#[test] +fn anchor_point_alt_drag_links_a_blend_spine_handle() { + let (d, id, sel) = blend_spine_doc(true); + let p = paint(); + let c = cx(&d, &sel, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let mut tool = AnchorTool::new("anchorPoint"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Down, 190.0, 330.0).with_mods(alt)); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Drag, 190.0, 350.0).with_mods(alt)); + assert_eq!( + actions.get(1), + Some(&Action::Preview( + "object.blend.spine.moveAnchor".into(), + json!({"id": id.0, "anchor": 1, "handle": "out", "x": 190.0, "y": 350.0, "link": true}) + )) + ); + assert_eq!(tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 190.0, 350.0).with_mods(alt)), vec![Action::Commit]); +} diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 75f0fde6d6..fac5bcd90b 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -37,7 +37,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_brush::{Calligraphic, Variation}; +use vectorcraft_brush::{BristleShape, BrushKind, Calligraphic, Variation}; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{Affine, BezPath, FillRule, ParamCurve, PathData, PathSeg, Point, Rect, Vec2, shapes}; use vectorcraft_pathops as po; @@ -200,6 +200,12 @@ pub struct GestureTool { /// Where the Blob Brush's or the Eraser's tip outline shows: the pointer over the canvas, /// unless Cmd/Ctrl lends a selection tool or Alt the Smooth tool. tip_at: Option, + /// Alt as it was at the last pointer event; the release can select a new path after the tool + /// returns, so the Bristle tip checks the current selection when overlays are drawn. + tip_alt: bool, + /// The last rotation-capable pen over the Paintbrush's Bristle tip; a mouse or a pen without + /// barrel rotation has no tip annotator. + bristle_pen: Option<(PenPose, f64)>, /// A pen pressed less than fully at a point of the stroke whose pressure is kept. light: bool, /// Which way the pen leaned at the last point of the stroke where it leaned 1° or more from @@ -899,6 +905,8 @@ impl GestureTool { snap: DrawSnap::default(), pressed: Point::ZERO, tip_at: None, + tip_alt: false, + bristle_pen: None, light: false, bearing: None, bearings: vec![], @@ -1088,12 +1096,50 @@ impl GestureTool { p } + fn pointer_tip(&mut self, cx: &ToolContext, ev: &PointerEvent) { + if self.varies_size() { + self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(ev.pos); + } else if self.id == "paintbrush" { + self.tip_alt = ev.mods.alt; + self.bristle_pen = + ev.pen.filter(|pen| pen.rotation.is_some()).map(|pen| (pen, if ev.kind == PointerKind::Move { 0.5 } else { f64::from(ev.pressure) })); + let borrows_smooth = !self.active && ev.mods.alt && has_selected_smooth_path(cx); + self.tip_at = self.bristle_pen.filter(|_| !ev.mods.cmd && !borrows_smooth).map(|_| ev.pos); + } + } + /// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline /// `size` across at its angle and roundness (the Eraser's as the pen varies them while it /// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on /// any art. Precise cursors show only the crosshair, and smoothing shows no tip. fn tip_outline(&self, cx: &ToolContext) -> Vec { let Some(at) = self.tip_at.filter(|_| !self.smoothing && !cx.precise_cursors) else { return vec![] }; + if self.id == "paintbrush" { + if !self.active && self.tip_alt && has_selected_smooth_path(cx) { + return vec![]; + } + let Some((pose, pressure)) = self.bristle_pen else { return vec![] }; + let Some(name) = vectorcraft_brush::current(cx.doc) else { return vec![] }; + let Some(brush) = vectorcraft_brush::find(cx.doc, &name) else { return vec![] }; + let BrushKind::Bristle(bristle) = brush.kind else { return vec![] }; + let [pressure, tilt, bearing, rotation] = super::pen_controls(pressure, Some(pose), super::pen_bearing(pose)); + let size = bristle.size.max(0.1) * cx.paint.stroke_width.max(0.0) * (0.5 + pressure) * (1.25 - 0.5 * tilt); + if size <= 0.0 { + return vec![]; + } + let roundness = match bristle.shape { + BristleShape::RoundFan | BristleShape::FlatFan => 0.25, + BristleShape::FlatPoint | BristleShape::FlatBlunt | BristleShape::FlatCurve | BristleShape::FlatAngle => 0.45, + _ => 0.8, + }; + let angle = std::f64::consts::TAU * (bearing + rotation - 1.0); + let circle = kurbo::Shape::to_path(&kurbo::Circle::new(Point::ORIGIN, size / 2.0), size.max(0.1) * 0.05); + let path = Affine::translate(at.to_vec2()) * Affine::rotate(-angle) * Affine::scale_non_uniform(1.0, roundness) * circle; + return vec![ + Overlay::Path { path: path.clone(), color: [0xff, 0xff, 0xff], width: 3.0, dashed: false }, + Overlay::Path { path, color: [0, 0, 0], width: 1.0, dashed: false }, + ]; + } let [angle, roundness, size] = self.tip_now(); let tip = if self.id == "blobBrush" { blob_tip(angle, roundness) } else { eraser_tip(angle, roundness) }; let r = size / 2.0; @@ -1587,9 +1633,7 @@ impl Tool for GestureTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; - if self.varies_size() { - self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p); - } + self.pointer_tip(cx, ev); if let Some(out) = self.marquee_pointer(cx, ev) { return out; } @@ -1762,6 +1806,10 @@ impl Tool for GestureTool { self.close_to = None; self.connect_to.clear(); self.redraw = None; + if self.id == "paintbrush" { + // The release can change a drawing stroke into an Alt-borrowed Smooth hover. + self.pointer_tip(cx, ev); + } out } _ => vec![], diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 3ebc50cd02..7ecc0bed03 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3043,6 +3043,103 @@ fn the_blob_brush_and_the_eraser_show_their_tip_at_the_pointer() { } } +/// A rotation-capable pen shows the current Bristle brush's tip before and during a Paintbrush +/// stroke. A mouse, a pen without rotation, precise cursors and a borrowed selection tool do not. +#[test] +fn bristle_tip_annotator_follows_a_rotation_capable_pen() { + let (mut d, id) = doc_with_rect(); + d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!("Bristle Flat Fan")); + let s = Selection::default(); + let p = paint(); + let view = cx(&d, &s, &p); + let bounds = |t: &GestureTool, cx: &ToolContext| { + let overlays = t.overlays(cx); + let Some(Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }) = overlays.last() else { return None }; + assert!(matches!(overlays.get(overlays.len() - 2), Some(Overlay::Path { color: [0xff, 0xff, 0xff], width: 3.0, .. }))); + Some(vectorcraft_geom::Shape::bounding_box(path)) + }; + let mut tool = GestureTool::new("paintbrush"); + let at = + |rotation| PointerEvent { pen: Some(PenPose { tilt: Some([30.0, 0.0]), rotation }), ..PointerEvent::new(PointerKind::Move, 100.0, 50.0) }; + assert!(bounds(&tool, &view).is_none()); + tool.pointer(&view, &PointerEvent::new(PointerKind::Move, 100.0, 50.0)); + assert!(bounds(&tool, &view).is_none(), "mouse"); + tool.pointer(&view, &at(None)); + assert!(bounds(&tool, &view).is_none(), "pen without rotation"); + tool.pointer(&view, &at(Some(0.0))); + let horizontal = bounds(&tool, &view).expect("rotating pen shows a tip"); + let mut selected = Selection::default(); + selected.set([id]); + let selected_view = cx(&d, &selected, &p); + tool.pointer(&selected_view, &at(Some(0.0)).with_mods(Mods { alt: true, ..Default::default() })); + assert!(bounds(&tool, &selected_view).is_none(), "Alt borrows Smooth for a selected path"); + tool.pointer(&view, &at(Some(0.0))); + let mut wider_paint = p.clone(); + wider_paint.stroke_width = 10.0; + let wider_view = cx(&d, &s, &wider_paint); + let wider = bounds(&tool, &wider_view).expect("stroke width scales the tip"); + assert!((wider.width() - horizontal.width() * 10.0).abs() < 1e-6, "{horizontal:?}, {wider:?}"); + wider_paint.stroke_width = 0.0; + assert!(bounds(&tool, &cx(&d, &s, &wider_paint)).is_none(), "a zero-width stroke has no tip"); + tool.pointer(&view, &at(Some(90.0))); + let vertical = bounds(&tool, &view).expect("tip turns with the barrel"); + assert!(horizontal.width() > horizontal.height() * 2.0, "{horizontal:?}"); + assert!(vertical.height() > vertical.width() * 2.0, "{vertical:?}"); + let mut light = at(Some(0.0)); + light.kind = PointerKind::Down; + light.pressure = 0.1; + tool.pointer(&view, &light); + let light_tip = bounds(&tool, &view).expect("light pressure shows a smaller tip"); + let mut heavy = light; + heavy.kind = PointerKind::Drag; + heavy.pressure = 0.9; + tool.pointer(&view, &heavy); + let heavy_tip = bounds(&tool, &view).expect("heavy pressure shows a larger tip"); + assert!(heavy_tip.width() > light_tip.width() * 1.5, "{light_tip:?}, {heavy_tip:?}"); + let mut release = heavy; + release.kind = PointerKind::Up; + tool.pointer(&view, &release); + let mut alt_stroke = light; + alt_stroke.pressure = 0.5; + tool.pointer(&selected_view, &alt_stroke); + alt_stroke.kind = PointerKind::Drag; + alt_stroke.mods.alt = true; + tool.pointer(&selected_view, &alt_stroke); + assert!(bounds(&tool, &selected_view).is_some(), "Alt during a drawing stroke keeps the tip"); + alt_stroke.kind = PointerKind::Up; + tool.pointer(&selected_view, &alt_stroke); + assert_eq!(tool.cursor(&selected_view, alt_stroke.pos, alt_stroke.mods), Cursor::Smooth); + assert!(bounds(&tool, &selected_view).is_none(), "Alt release borrows Smooth without a stale tip"); + // A completed stroke can select its new path after `pointer` returns its actions. The overlay + // must use that current selection even without a further pointer move. + let mut newly_selected = GestureTool::new("paintbrush"); + let mut new_stroke = light; + newly_selected.pointer(&view, &new_stroke); + new_stroke.kind = PointerKind::Drag; + new_stroke.mods.alt = true; + newly_selected.pointer(&view, &new_stroke); + new_stroke.kind = PointerKind::Up; + newly_selected.pointer(&view, &new_stroke); + assert!(bounds(&newly_selected, &view).is_some(), "no selected path borrows Smooth yet"); + assert_eq!(newly_selected.cursor(&selected_view, new_stroke.pos, new_stroke.mods), Cursor::Smooth); + assert!(bounds(&newly_selected, &selected_view).is_none(), "post-commit selection also hides the tip"); + tool.pointer(&view, &at(Some(0.0))); + assert!(bounds(&tool, &view).is_some(), "a normal pen hover shows the tip before Precise Cursors hides it"); + let precise = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + assert!(bounds(&tool, &precise).is_none()); + tool.pointer(&view, &at(Some(0.0)).with_mods(Mods { cmd: true, ..Default::default() })); + assert!(bounds(&tool, &view).is_none(), "selection tool borrowed by Cmd"); + tool.pointer(&view, &at(Some(0.0))); + tool.hover_ended(&view); + assert!(bounds(&tool, &view).is_none(), "leaving the canvas"); + + let (mut d, _) = doc_with_rect(); + d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!("3 pt. Round")); + let calligraphic = cx(&d, &s, &p); + tool.pointer(&calligraphic, &at(Some(0.0))); + assert!(bounds(&tool, &calligraphic).is_none(), "other brush types keep their cursor"); +} + /// Eraser Tool Options' Angle, Roundness and Size variation menus: the Eraser keeps each mode and /// Variation, the release sends them with the pen's readings along the drag, and while it erases /// its tip outline at the pointer takes the angle, roundness and size the pen gives there. The Blob diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 5eed055eaa..d9d210096e 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -6,7 +6,9 @@ //! on macOS) draws a flare there with them at once), then a click sets the //! end point of the rings (↑/↓ add or remove rings and ~ places them anew); Space held during //! either drag moves the flare. The rest comes -//! from the tool's options (the Flare Tool Options, which last). Reshape: a click on a selected +//! from the tool's options (the Flare Tool Options, which last). With one flare selected, the tool +//! shows its center and end handles, and dragging either changes the flare's length and direction +//! (`shape.editFlare`). Reshape: a click on a selected //! path sets a focal point (adding an anchor on a segment), Shift-click adds or removes more, and //! a drag from a focal point moves them all; the engine's `path.reshape` stretches the selected //! anchors between them and the anchors that stay. @@ -83,6 +85,40 @@ pub struct FlareTool { /// Whether the flare has rays and rings (the options' Rays and Rings checkboxes). rays_on: bool, rings_on: bool, + /// A drag of the selected flare's center or end handle. + handle: Option, +} + +/// A drag of a selected flare's handle: the flare, whether it is the end handle (else the center), +/// where the handle was, where it was pressed, whether Alt (Option on macOS) was held at the press +/// and whether the drag has begun its undo step. +#[derive(Clone, Copy, Debug)] +struct HandleDrag { + id: vectorcraft_doc::NodeId, + end: bool, + from: Point, + at: Point, + alt: bool, + began: bool, +} + +/// The flare whose handles the Flare tool shows: the one selected object, when it is a flare that +/// can be edited, with its center and the rings' end point. +fn selected_flare(cx: &ToolContext) -> Option<(vectorcraft_doc::NodeId, Point, Point)> { + let [id] = cx.selection.objects.as_slice() else { return None }; + if !cx.doc.is_editable(*id) { + return None; + } + let node = cx.doc.node(*id)?; + let spec = node.extras().flare.as_deref().filter(|spec| spec.draws(node))?; + Some((*id, spec.center()?, spec.end()?)) +} + +/// `shape.editFlare`'s params for handle drag `h` with the pointer at `pointer`: the handle moves +/// as far as the pointer has. +fn handle_params(h: HandleDrag, pointer: Point) -> Value { + let p = h.from + (pointer - h.at); + if h.end { json!({ "ids": [h.id.0], "x2": p.x, "y2": p.y }) } else { json!({ "ids": [h.id.0], "cx": p.x, "cy": p.y }) } } impl Default for FlareTool { @@ -104,6 +140,7 @@ impl Default for FlareTool { values: FLARE_OPTIONS.map(|(_, default, _, _)| default), rays_on: true, rings_on: true, + handle: None, } } } @@ -251,7 +288,7 @@ impl Tool for FlareTool { "flare" } fn busy(&self) -> bool { - self.drag.is_some() || self.placed.is_some() + self.drag.is_some() || self.placed.is_some() || self.handle.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.hover = ev.pos; @@ -261,8 +298,43 @@ impl Tool for FlareTool { if quote_pressed && self.rings_on && self.placed.is_some() && matches!(ev.kind, PointerKind::Drag | PointerKind::Move | PointerKind::Up) { self.ring_seed = Some(next_ring_seed(self.ring_seed, ev.pos)); } + if let Some(mut h) = self.handle { + return match ev.kind { + PointerKind::Drag if h.began => vec![Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos))], + PointerKind::Drag if ev.pos.distance(h.at) < cx.tol(3.0) => vec![], + PointerKind::Drag => { + h.began = true; + self.handle = Some(h); + vec![Action::Begin("Edit Flare".into()), Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos))] + } + PointerKind::Up => { + self.handle = None; + if h.began { + vec![Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos)), Action::Commit] + } else if h.alt { + // A click on a handle without a drag is a click with the tool. + self.click_flare(cx, h.at) + } else { + vec![Action::Dialog("flare".into(), json!({ "x": h.at.x, "y": h.at.y }))] + } + } + _ => vec![], + }; + } match ev.kind { PointerKind::Down => { + // A press on the selected flare's center or end handle drags that handle. + if self.placed.is_none() + && let Some((id, c, e)) = selected_flare(cx) + { + let tol = cx.tol(4.0); + let (dc, de) = (ev.pos.distance(c), ev.pos.distance(e)); + if dc.min(de) <= tol { + let end = de < dc; + self.handle = Some(HandleDrag { id, end, from: if end { e } else { c }, at: ev.pos, alt: ev.mods.alt, began: false }); + return vec![]; + } + } if self.placed.is_none() { self.drag = Some((ev.pos, ev.pos)); self.rays = None; @@ -350,6 +422,11 @@ impl Tool for FlareTool { }; return vec![Action::Preview("shape.flare".into(), preview)]; } + if key == ToolKey::Escape + && let Some(h) = self.handle.take() + { + return if h.began { vec![Action::Cancel] } else { vec![] }; + } if key == ToolKey::Escape && self.busy() { self.rays = None; self.rings = None; @@ -367,16 +444,27 @@ impl Tool for FlareTool { // Switching away after the centre drag keeps the flare with the rings its options give. self.drag = None; self.held = None; + if self.handle.take().is_some_and(|h| h.began) { + return vec![Action::Commit]; + } if self.placed.take().is_some() && std::mem::take(&mut self.began) { vec![Action::Commit] } else { vec![] } } - fn overlays(&self, _cx: &ToolContext) -> Vec { + fn overlays(&self, cx: &ToolContext) -> Vec { match (self.drag, self.placed) { (Some((c, p)), _) => { let r = self.center_diameter(p.distance(c)) / 2.0; vec![Overlay::Path { path: ellipse_path(c, r, r, 0.0), color: BLUE, width: 1.0, dashed: false }] } (_, Some((c, _))) => vec![Overlay::Line { a: c, b: self.hover, color: BLUE, dashed: true }], - _ => vec![], + // The selected flare's center and end handles. + _ => match selected_flare(cx) { + Some((_, c, e)) => vec![ + Overlay::Line { a: c, b: e, color: BLUE, dashed: true }, + Overlay::Anchor { p: c, color: BLUE, filled: self.handle.is_some_and(|h| !h.end), size: 7.0 }, + Overlay::Anchor { p: e, color: BLUE, filled: self.handle.is_some_and(|h| h.end), size: 7.0 }, + ], + None => vec![], + }, } } fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { @@ -1021,6 +1109,69 @@ mod tests { assert_eq!(t.turn, 10.0); } + /// With one flare selected, the tool shows its center and end handles where the flare is now + /// drawn, and dragging either edits the flare (`shape.editFlare`) as one undo step; a press + /// away from them draws a new flare. + #[test] + fn dragging_a_selected_flares_handles_changes_its_length_and_direction() { + use crate::testutil::*; + use vectorcraft_doc::flare::{FlareSpec, part_node, parts}; + use vectorcraft_doc::{Node, Selection}; + let (mut d, _) = doc_with_rect(); + let gid = d.alloc_id(); + let v = json!({ "cx": 100.0, "cy": 100.0, "x2": 300.0, "y2": 100.0, "rays": 3, "rings": 2, "seed": 5, "diameter": 30.0, + "opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0, + "rotation": 0.0, "largest": 50.0 }); + let xf = vectorcraft_geom::Affine::translate((10.0, 20.0)); + let children: Vec<_> = parts(&v).into_iter().map(|part| std::sync::Arc::new(part_node(d.alloc_id(), part, xf, false))).collect(); + let edited = children[0].id; + let mut g = Node::group(gid, children); + g.extras_mut().flare = Some(Box::new(FlareSpec { params: v, transform: xf })); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, g).unwrap_or_else(|e| panic!("{e}")); + let s = Selection { objects: vec![gid], ..Default::default() }; + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = FlareTool::default(); + let ov = t.overlays(&cx); + let anchors: Vec = ov.iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(*p) } else { None }).collect(); + assert_eq!(anchors, vec![Point::new(110.0, 120.0), Point::new(310.0, 120.0)]); + // The end handle, grabbed 2 points off: it moves as far as the pointer. + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 312.0, 120.0)).is_empty()); + assert!(t.busy()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 312.0, 160.0)); + assert_eq!(a.first(), Some(&Action::Begin("Edit Flare".into()))); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 302.0, 200.0)); + assert_eq!(a, vec![Action::Preview("shape.editFlare".into(), json!({ "ids": [gid.0], "x2": 300.0, "y2": 200.0 })), Action::Commit]); + // The center handle; Escape cancels its drag. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 121.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 121.0)); + assert_eq!(a.last(), Some(&Action::Preview("shape.editFlare".into(), json!({ "ids": [gid.0], "cx": 150.0, "cy": 120.0 })))); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(!t.busy()); + // A click on a handle without a drag is a click with the tool: it opens the dialog, and + // with Alt held it draws a flare there with the tool's options. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 120.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 120.0)); + assert_eq!(a, vec![Action::Dialog("flare".into(), json!({ "x": 110.0, "y": 120.0 }))]); + assert!(!t.busy()); + let alt = Mods { alt: true, ..Default::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 310.0, 121.0).with_mods(alt)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 310.0, 121.0).with_mods(alt)); + assert_eq!(a, vec![Action::Exec("shape.flare".into(), flare_params(&t.options(), Point::new(310.0, 121.0)))]); + assert!(!t.busy()); + // Away from the handles a drag draws a new flare. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 300.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 240.0, 300.0)); + assert_eq!(a.first(), Some(&Action::Begin("Flare".into()))); + // Without a flare selected, no handles show. + let none = Selection::default(); + assert!(FlareTool::default().overlays(&crate::testutil::cx(&d, &none, &p)).is_empty()); + // A flare with an edited part is no longer edited as a flare: no handles show. + d.node_mut(edited).unwrap_or_else(|| panic!("no part")).opacity = 0.25; + assert!(FlareTool::default().overlays(&crate::testutil::cx(&d, &s, &p)).is_empty()); + } + /// Space held while dragging out a flare moves it at its current size and turn, in the center /// drag and in the drag that places the rings' end point; let go, the drag goes on from there. #[test] diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 43e59de7da..0b7bef755f 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -42,6 +42,7 @@ pub mod select; pub mod settings; pub mod shape; pub mod shaperwidget; +pub mod sidewidget; pub mod slice; pub mod symbolism; pub mod text; @@ -104,6 +105,10 @@ pub enum Overlay { Swatch { p: Point, color: [u8; 4], selected: bool }, /// A hairline in a translucent colour (perspective gridlines), RGBA. GridLine { a: Point, b: Point, color: [u8; 4] }, + /// Hover text for the disc of `radius` (document units) around `center`: while the pointer + /// rests there and nothing is being dragged, the UI shows `text`, an English UI string it + /// translates, as a tooltip. Nothing is drawn for it. + HoverText { center: Point, radius: f64, text: &'static str }, } /// What an IME's "delete the text around the cursor" counts: UTF-8 bytes (winit's raw @@ -674,6 +679,19 @@ pub(crate) mod testutil { global_edit: &[], } } + + /// Held for reading by tests that count the layouts the Type tool keeps, and for writing by + /// tests that change what layout reads (fonts, hyphenation exceptions): tests run in parallel, + /// and a count must not include a refresh another test caused. + static LAYOUT_INPUTS: std::sync::RwLock<()> = std::sync::RwLock::new(()); + + pub fn steady_layout_inputs() -> std::sync::RwLockReadGuard<'static, ()> { + LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner()) + } + + pub fn changing_layout_inputs() -> std::sync::RwLockWriteGuard<'static, ()> { + LAYOUT_INPUTS.write().unwrap_or_else(|e| e.into_inner()) + } } #[cfg(test)] diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index 0322c82ca3..7b12599b62 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -631,7 +631,7 @@ impl PenTool { if !alt_converts(cx, ev.pos, ev.mods) { return None; } - let mut t = AnchorTool::new("anchorPoint"); + let mut t = AnchorTool::lent_by_pen(); let acts = t.pointer(cx, ev); if !t.busy() { return None; diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 079de9ed06..e9c3e2bb03 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -54,6 +54,7 @@ use crate::pathtype::{self, BracketDrag, over_bracket}; use crate::pie::{self, PieDrag}; use crate::rulerguide::GuideEdit; use crate::shaperwidget; +use crate::sidewidget::{self, SideDrag}; use crate::typewidget; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids}; @@ -134,6 +135,8 @@ enum State { Corner(CornerDrag), /// Dragging a live ellipse's pie widget. Pie(PieDrag), + /// Dragging a live polygon's side widget. + Sides(SideDrag), /// Dragging a selected blend's Appearance or Easing widget. BlendWidget(BlendWidgetDrag), /// Dragging an Objects on Path group's Rotate All widget. @@ -827,7 +830,7 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or - /// rotation, a marquee, a corner widget, a pie widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror + /// rotation, a marquee, a corner widget, a pie widget, a polygon's side widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. @@ -864,6 +867,12 @@ impl Tool for SelectionTool { { return d.cancel(); } + if key == ToolKey::Escape + && matches!(self.state, State::Sides(_)) + && let State::Sides(d) = std::mem::take(&mut self.state) + { + return d.cancel(); + } if key == ToolKey::Escape && matches!(self.state, State::NineSlice(_)) && let State::NineSlice(d) = std::mem::take(&mut self.state) @@ -896,11 +905,15 @@ impl Tool for SelectionTool { out } - /// Switching tools during a blend widget's drag cancels it, as Escape does: its value goes back. + /// Switching tools during a drag of a blend widget, a corner widget, a pie widget or a + /// polygon's side widget cancels it, as Escape does: its value goes back. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { match std::mem::take(&mut self.state) { State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel], - State::BlendWidget(_) => vec![], + State::Corner(c) if c.adjusting() => vec![Action::Cancel], + State::Pie(d) if d.adjusting() => vec![Action::Cancel], + State::Sides(d) => d.cancel(), + State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![], other => { self.state = other; vec![] @@ -947,6 +960,7 @@ impl Tool for SelectionTool { State::Moving { began: true, .. } | State::Scaling { .. } | State::Rotating { .. } => true, State::Corner(c) => c.adjusting(), State::Pie(d) => d.adjusting(), + State::Sides(d) => d.adjusting(), State::BlendWidget(d) => d.adjusting(), State::RotateAll(d) => d.adjusting(), State::Space(d) => d.adjusting(), @@ -1126,6 +1140,15 @@ impl Tool for SelectionTool { self.state = State::Idle; d.finish() } + (PointerKind::Drag, State::Sides(mut d)) => { + let out = d.drag(cx, p); + self.state = State::Sides(d); + out + } + (PointerKind::Up, State::Sides(d)) => { + self.state = State::Idle; + d.finish() + } (PointerKind::Drag, State::BlendWidget(mut d)) => { let out = d.drag(cx, p); self.state = State::BlendWidget(d); @@ -1233,6 +1256,7 @@ impl Tool for SelectionTool { }), State::Corner(c) => o.extend(c.overlays(cx)), State::Pie(d) => o.extend(d.overlays(cx)), + State::Sides(d) => o.extend(d.overlays(cx)), State::BlendWidget(d) => o.extend(d.overlays(cx)), State::RotateAll(d) => o.extend(d.overlays(cx)), State::Space(d) => o.extend(d.overlays(cx)), @@ -1292,7 +1316,7 @@ impl Tool for SelectionTool { State::Moving { began: true, .. } if m.alt => return Cursor::SelectionCopy, State::Moving { began: true, .. } => return if self.snapped { Cursor::ArrowHollow } else { Cursor::Arrow }, State::Corner(_) => return Cursor::CornerRadius, - State::Pie(_) | State::BlendWidget(_) => return Cursor::ArrowHollow, + State::Pie(_) | State::Sides(_) | State::BlendWidget(_) => return Cursor::ArrowHollow, State::RotateAll(_) => return Cursor::Rotate, State::Space(_) => return Cursor::ArrowHollow, State::MoveAll(_) | State::Member(_) => return Cursor::Move, @@ -1323,6 +1347,9 @@ impl Tool for SelectionTool { if near_selected && pie::over_widget(cx, p) { return Cursor::ArrowHollow; } + if sidewidget::over_widget(cx, p) { + return Cursor::ArrowHollow; + } if blendwidget::over_widget(cx, p) { return Cursor::ArrowHollow; } @@ -1385,11 +1412,17 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option { /// object selected whole between it and the art under the pointer, such as members of a group /// picked with Group Selection. A press there keeps the selection and a drag moves it (#8047). A /// member with only some anchors or segments selected does not count: the press selects `top`. +/// A member with every anchor selected (as `select.anchors` and `select.key` leave a path) counts. fn selected_under(cx: &ToolContext, h: &Hit, top: NodeId) -> Option { if cx.selection.contains(top) { return Some(top); } - let whole = |id: NodeId| cx.selection.contains(id) && cx.selection.partial(id).is_none() && !cx.selection.segments.contains_key(&id); + let every_anchor = |id: NodeId| { + cx.selection + .partial(id) + .is_none_or(|picked| cx.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().all(|(s, i, _)| picked.contains(&(s, i))))) + }; + let whole = |id: NodeId| cx.selection.contains(id) && every_anchor(id) && !cx.selection.segments.contains_key(&id); let below = h.ancestry.iter().position(|id| *id == top).map_or(&[][..], |i| h.ancestry.get(i..).unwrap_or_default()); below.iter().copied().chain(std::iter::once(h.leaf)).find(|id| whole(*id)) } @@ -1689,6 +1722,10 @@ impl SelectionTool { if blendwidget::over_widget(cx, p) { return vec![]; } + // A live polygon's side widget takes a plain double-click the same way. + if sidewidget::over_widget(cx, p) { + return vec![]; + } if crate::rulerguide::guide_at(cx, p).is_some() { return vec![]; } @@ -1728,7 +1765,7 @@ impl SelectionTool { self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None }; return Some(vec![]); } - // 1. Live Corners widgets, pie widgets, blend widgets, the Rotate All, Space, Move All and Select/Move widgets and type on a path's brackets, then the + // 1. Live Corners widgets, pie widgets, a polygon's side widget, blend widgets, the Rotate All, Space, Move All and Select/Move widgets and type on a path's brackets, then the // bounding-box handles of the current selection. if let Some(c) = CornerDrag::hit(cx, ev, false) { self.state = State::Corner(c); @@ -1738,6 +1775,10 @@ impl SelectionTool { self.state = State::Pie(d); return Some(vec![]); } + if let Some(d) = SideDrag::hit(cx, ev) { + self.state = State::Sides(d); + return Some(vec![]); + } if let Some(d) = BlendWidgetDrag::hit(cx, ev) { self.state = State::BlendWidget(d); return Some(vec![]); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index a39c528a1d..5c52201a6f 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2889,4 +2889,12 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() { let c = cx(&d, &s, &p); let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 125.0)); assert_eq!(down, vec![Action::Exec("select.set".into(), json!({"ids": [outer.0]}))]); + // Every anchor of the member picked (as `select.anchors` and `select.key` leave it) selects + // it whole: the press moves it. + s.anchors.insert(a, [(0, 0), (0, 1), (0, 2), (0, 3)].into_iter().collect()); + let c = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "every anchor"); + let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0)); + assert!(!is_select(&down), "every anchor: {down:?}"); } diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index d4c8d4f36c..6685dd20f2 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -25,7 +25,8 @@ //! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, //! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at //! once: a drag on a live rectangle's or polygon's corner widget rounds its corners and a drag on -//! a live ellipse's pie widget sets its pie angle, as with the Selection tool; a drag on one of the +//! a live ellipse's pie widget sets its pie angle and a drag on a live polygon's side widget sets +//! its number of sides, as with the Selection tool; a drag on one of the //! box's eight handles scales the selection, a press on the selection's centre point (Show Center) //! moves it, and one just outside a corner of its box turns it about that centre, as the Selection //! tool's handles, centre point and rotate zone do; a press anywhere else draws a new shape (#5477). @@ -43,6 +44,7 @@ use crate::corners::{self, CornerDrag}; use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square}; use crate::pie::{self, PieDrag}; use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box}; +use crate::sidewidget::{self, SideDrag}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The largest corner radius the Rounded Rectangle tool draws, points: the range of General › @@ -84,6 +86,7 @@ pub fn shows_shape_widgets(id: &str) -> bool { enum WidgetDrag { Corner(CornerDrag), Pie(PieDrag), + Sides(SideDrag), } /// A drag of the selection itself, taken by a shape tool: a handle of its box scales it, the centre @@ -294,18 +297,21 @@ impl ShapeTool { self.star_ratio = o.star_ratio; } - /// A press on a corner or pie widget of the selection: the drag adjusts it. + /// A press on a corner, pie or side widget of the selection: the drag adjusts it. fn press_widget(&mut self, cx: &ToolContext, ev: &PointerEvent) -> bool { if !shows_shape_widgets(self.id) { return false; } - self.widget = CornerDrag::hit(cx, ev, false).map(WidgetDrag::Corner).or_else(|| PieDrag::hit(cx, ev).map(WidgetDrag::Pie)); + self.widget = CornerDrag::hit(cx, ev, false) + .map(WidgetDrag::Corner) + .or_else(|| PieDrag::hit(cx, ev).map(WidgetDrag::Pie)) + .or_else(|| SideDrag::hit(cx, ev).map(WidgetDrag::Sides)); self.widget.is_some() } - /// Is `p` over a corner or pie widget of the selection that a press would drag? + /// Is `p` over a corner, pie or side widget of the selection that a press would drag? fn over_widget(&self, cx: &ToolContext, p: Point) -> bool { - shows_shape_widgets(self.id) && (corners::over_widget(cx, p, false) || pie::over_widget(cx, p)) + shows_shape_widgets(self.id) && (corners::over_widget(cx, p, false) || pie::over_widget(cx, p) || sidewidget::over_widget(cx, p)) } /// The selection's box, while this tool shows it (the tools that draw a box, with a selection @@ -481,10 +487,12 @@ impl ShapeTool { PointerKind::Drag => match w { WidgetDrag::Corner(c) => c.drag(cx, ev.pos), WidgetDrag::Pie(d) => d.drag(cx, ev.pos), + WidgetDrag::Sides(d) => d.drag(cx, ev.pos), }, PointerKind::Up => match self.widget.take() { Some(WidgetDrag::Corner(c)) => c.finish(), Some(WidgetDrag::Pie(d)) => d.finish(), + Some(WidgetDrag::Sides(d)) => d.finish(), None => vec![], }, _ => vec![], @@ -823,6 +831,12 @@ impl Tool for ShapeTool { _ => vec![], } } + /// Switching tools during a drag of a corner, pie or side widget cancels it, as Escape does: + /// the shape goes back. + fn deactivate(&mut self, cx: &ToolContext) -> Vec { + if self.widget.is_some() { self.key(cx, ToolKey::Escape, Mods::default()) } else { vec![] } + } + /// ↑/↓ change a polygon's sides, a star's points or the rounded rectangle's radius while it is /// drawn; Escape turns a widget or selection drag back. fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { @@ -838,6 +852,7 @@ impl Tool for ShapeTool { (ToolKey::Escape, _) => match self.widget.take() { Some(WidgetDrag::Corner(c)) if c.adjusting() => vec![Action::Cancel], Some(WidgetDrag::Pie(d)) if d.adjusting() => vec![Action::Cancel], + Some(WidgetDrag::Sides(d)) => d.cancel(), _ => vec![], }, _ => vec![], @@ -920,6 +935,7 @@ impl Tool for ShapeTool { match &self.widget { Some(WidgetDrag::Corner(c)) => c.adjusting(), Some(WidgetDrag::Pie(d)) => d.adjusting(), + Some(WidgetDrag::Sides(d)) => d.adjusting(), None => match &self.selection { Some(SelectionDrag::Move { began, .. }) => *began, Some(SelectionDrag::Rotate { .. } | SelectionDrag::Scale { .. }) => true, @@ -956,6 +972,7 @@ impl Tool for ShapeTool { match &self.widget { Some(WidgetDrag::Corner(c)) => return c.overlays(cx), Some(WidgetDrag::Pie(d)) => return d.overlays(cx), + Some(WidgetDrag::Sides(d)) => return d.overlays(cx), None => {} } // A line on a common tangent shows that snap's guides, and its length and angle. @@ -1017,7 +1034,7 @@ impl Tool for ShapeTool { let idle = self.start.is_none(); match &self.widget { Some(WidgetDrag::Corner(_)) => return Cursor::CornerRadius, - Some(WidgetDrag::Pie(_)) => return Cursor::ArrowHollow, + Some(WidgetDrag::Pie(_) | WidgetDrag::Sides(_)) => return Cursor::ArrowHollow, None => {} } // Alt-dragging the selection leaves a copy behind; otherwise the arrow, hollow while the diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index ec911f4cfb..d52cf374d4 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1309,6 +1309,114 @@ fn a_shape_tool_drags_the_selected_shapes_widgets() { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 20.0)), vec![Action::Commit]); } +/// With a shape tool, a drag down on a selected live polygon's side widget adds sides instead of +/// drawing, and Escape puts the count back; Line Segment draws from the widget. +#[test] +fn a_shape_tool_drags_a_polygons_side_widget() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let shape = + LiveShape::Polygon { radius: 80.0, sides: 5, xf: Affine::translate((250.0, 250.0)), radii: vec![], kinds: vec![], radii_relative: false }; + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = crate::sidewidget::SideWidget::for_tool(&c).expect("a side widget"); + let down = |px: f64| PointerEvent::new(PointerKind::Drag, w.at.x, w.at.y + px); + for tool in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + let mut t = ShapeTool::new(tool); + assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::ArrowHollow, "{tool}"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)).is_empty(), "{tool}"); + let a = t.pointer(&c, &down(25.0)); + assert_eq!( + a, + vec![Action::Begin("Live Shape".into()), Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 7 }))], + "{tool}" + ); + assert!(t.transforming() && !t.drawing_boxed(), "{tool}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, w.at.x, w.at.y + 25.0)), vec![Action::Commit], "{tool}"); + assert!(!t.busy(), "{tool}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)); + t.pointer(&c, &down(-13.0)); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{tool}"); + assert!(!t.busy(), "{tool}"); + } + let mut t = ShapeTool::new("lineSegment"); + assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::Crosshair); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)); + let a = t.pointer(&c, &down(25.0)); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd == "shape.line"), "{a:?}"); +} + +/// Switching away from a shape tool or the Selection tool during a drag of a corner, pie or side +/// widget cancels it, as Escape does: the shape goes back. After a press that has not moved there +/// is nothing to put back. +#[test] +fn a_tool_switch_cancels_a_widget_drag() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = |shape: LiveShape| { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, s) + }; + let xf = Affine::translate((100.0, 100.0)); + let rect = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let ellipse = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let polygon = live(LiveShape::Polygon { + radius: 80.0, + sides: 5, + xf: Affine::translate((250.0, 250.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }); + let p = paint(); + let side = crate::sidewidget::SideWidget::for_tool(&cx(&polygon.0, &polygon.1, &p)).expect("a side widget").0.at; + // The corner widget at (110, 110), the pie widget 12 px right of (300, 150), the side widget. + let drags = [ + (&rect, Point::new(110.0, 110.0), Point::new(130.0, 130.0)), + (&ellipse, Point::new(312.0, 150.0), Point::new(200.0, 20.0)), + (&polygon, side, side + Vec2::new(0.0, 25.0)), + ]; + for ((d, s), at, to) in drags { + let c = cx(d, s, &p); + let tools: [Box; 6] = [ + Box::new(crate::select::SelectionTool::default()), + Box::new(ShapeTool::new("rectangle")), + Box::new(ShapeTool::new("roundedRectangle")), + Box::new(ShapeTool::new("ellipse")), + Box::new(ShapeTool::new("polygon")), + Box::new(ShapeTool::new("star")), + ]; + for mut t in tools { + let id = t.id(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty(), "{id} at {at:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert!(matches!(a.first(), Some(Action::Begin(_))), "{id} at {at:?}: {a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel], "{id} at {at:?}"); + assert!(!t.busy() && !t.transforming(), "{id} at {at:?}"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, to.x, to.y)).is_empty(), "{id} at {at:?}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(t.busy(), "{id} at {at:?}"); + assert!(t.deactivate(&c).is_empty(), "{id} at {at:?}"); + assert!(!t.busy(), "{id} at {at:?}"); + } + } +} + /// A double-click on a corner widget of a selected live shape, with a shape tool that shows the /// widgets, asks for the Transform panel and nothing else: neither click draws, edits or begins an /// undo step, and the tool stays idle. Line Segment, a plain path, a pie widget, a hidden or diff --git a/crates/tools/src/sidewidget.rs b/crates/tools/src/sidewidget.rs new file mode 100644 index 0000000000..7928238d51 --- /dev/null +++ b/crates/tools/src/sidewidget.rs @@ -0,0 +1,432 @@ +//! The side widget: a small diamond beside the right side of a selected live polygon's bounding +//! box (). +//! Dragging it down adds sides and dragging it up removes them, one side per [`STEP_PX`] screen +//! pixels along the box's own vertical axis, from 3 to 11 sides. A polygon with more than 11 +//! sides keeps its count until the drag goes up a step, which gives it 11. The drag sends +//! `object.setLiveShape`'s `sides` in one undo step, and none when the count ends where it began. +//! The Selection tool and the shape tools that show the box hit the widget, and the canvas draws it +//! from the same geometry. + +use serde_json::json; +use vectorcraft_doc::{Document, LiveShape, NodeId, NodeKind, OrientedBox, Selection}; +use vectorcraft_geom::Point; + +use crate::select::shown_box; +use crate::{Action, Overlay, PointerEvent, ToolContext}; + +/// The widget's center sits this far (screen px) outside the middle of the box's right side, clear +/// of its handle. +const OFFSET_PX: f64 = 16.0; +/// Half the widget's diagonal (screen px), as the canvas draws it. +pub const RADIUS_PX: f32 = 4.0; +/// How near (screen px) the pointer must be to hit it. +const HIT_PX: f64 = 5.0; +/// How far (screen px) the pointer moves along the box's vertical axis per side. +pub const STEP_PX: f64 = 12.0; +/// The fewest sides a drag gives. +pub const MIN_SIDES: u32 = 3; +/// The most sides a drag gives. +pub const MAX_SIDES: u32 = 11; + +/// The side widget of a selection that is exactly one editable live polygon. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SideWidget { + pub id: NodeId, + /// Center in document coordinates. + pub at: Point, + /// The polygon's side count. + pub sides: u32, +} + +impl SideWidget { + /// The widget beside `bx`, the selection's bounding box, at `zoom` (screen px per document + /// point). None unless the selection is one whole editable live polygon, with no anchors or + /// segments of it selected. + pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option { + let [id] = selection.objects[..] else { return None }; + if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !doc.is_editable(id) || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let NodeKind::Path { live, .. } = &doc.node(id)?.kind else { return None }; + let Some(LiveShape::Polygon { sides, .. }) = live.as_deref() else { return None }; + let r = bx.rect; + let at = bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y); + (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides }) + } + + /// The widget the tool can drag (its bounding box showing). + pub fn for_tool(cx: &ToolContext) -> Option<(Self, OrientedBox)> { + // One object or none: a larger selection's box is not measured. + if cx.selection.objects.len() != 1 { + return None; + } + let bx = shown_box(cx)?; + Some((Self::of(cx.doc, cx.selection, &bx, cx.zoom)?, bx)) + } + + /// The widget of `cx` and its box if the widget is under `p`. + fn at(cx: &ToolContext, p: Point) -> Option<(Self, OrientedBox)> { + Self::for_tool(cx).filter(|(w, _)| w.at.distance(p) <= cx.tol(HIT_PX)) + } +} + +/// Is `p` over the side widget? +pub fn over_widget(cx: &ToolContext, p: Point) -> bool { + SideWidget::at(cx, p).is_some() +} + +/// The side count a drag of `steps` (down positive) gives a polygon of `from` sides: within 3 to 11, +/// and `from` itself while a polygon of more than 11 sides has not been dragged up. +pub fn sides_after(from: u32, steps: i64) -> u32 { + let (min, max) = (i64::from(MIN_SIDES), i64::from(MAX_SIDES)); + let to = if from <= MAX_SIDES { + i64::from(from).saturating_add(steps) + } else if steps >= 0 { + return from; + } else { + (max + 1).saturating_add(steps) + }; + to.clamp(min, max) as u32 +} + +/// Dragging the side widget. +#[derive(Clone, Debug)] +pub struct SideDrag { + widget: SideWidget, + bx: OrientedBox, + start: Point, + /// The pointer has left the click. + moved: bool, + /// The undo step has begun: the count has differed from the polygon's. + began: bool, + /// The count last sent (the polygon's until the drag changes it). + sides: u32, + at: Point, +} + +impl SideDrag { + /// The drag has left the click. + pub fn adjusting(&self) -> bool { + self.moved + } + + /// Start a drag when the press `ev` is on the side widget of the selection. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let (widget, bx) = SideWidget::at(cx, ev.pos)?; + Some(Self { widget, bx, start: ev.pos, moved: false, began: false, sides: widget.sides, at: ev.pos }) + } + + /// A pointer position that is not finite leaves the count and the readout as they are. A drag + /// too long to measure counts as the most steps in its direction. + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !p.x.is_finite() || !p.y.is_finite() { + return vec![]; + } + self.at = p; + if !self.moved { + if p.distance(self.start) < cx.tol(3.0) { + return vec![]; + } + self.moved = true; + } + let down = (self.bx.to_local(p).y - self.bx.to_local(self.start).y) * cx.zoom; + let steps = (down / STEP_PX).trunc(); + if steps.is_nan() { + return vec![]; + } + // The cast saturates: an infinite count of steps becomes i64::MAX or i64::MIN. + let sides = sides_after(self.widget.sides, steps as i64); + if sides == self.sides { + return vec![]; + } + let mut out = vec![]; + if !self.began { + self.began = true; + out.push(Action::Begin("Live Shape".into())); + } + self.sides = sides; + out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, "sides": sides }))); + out + } + + /// The release: one undo step when the count changed, and nothing kept when it came back. + pub fn finish(self) -> Vec { + match (self.began, self.sides == self.widget.sides) { + (false, _) => vec![], + (true, true) => vec![Action::Cancel], + (true, false) => vec![Action::Commit], + } + } + + /// Escape: the polygon keeps the count it had. + pub fn cancel(self) -> Vec { + if self.began { vec![Action::Cancel] } else { vec![] } + } + + /// The side count next to the pointer. + pub fn overlays(&self, cx: &ToolContext) -> Vec { + if !self.moved || !cx.measurement_labels { + return vec![]; + } + vec![Overlay::Measure { p: self.at, text: format!("Sides: {}", self.sides) }] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::select::SelectionTool; + use crate::testutil::*; + use crate::{Cursor, Mods, PointerKind, Tool, ToolKey}; + use vectorcraft_doc::{Appearance, Node}; + use vectorcraft_geom::Affine; + + /// A document holding a live polygon of `sides` sides and radius 100 placed by `xf`, and a + /// selection of it. + fn polygon_doc(sides: u32, xf: Affine) -> (Document, NodeId, Selection) { + let live = LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + let mut d = Document::new(800.0, 800.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut n = Node::path(id, live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(live)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, id, s) + } + + fn ev(kind: PointerKind, p: Point) -> PointerEvent { + PointerEvent::new(kind, p.x, p.y) + } + + fn sides_of(a: &[Action]) -> Vec { + a.iter().filter_map(|a| if let Action::Preview(_, v) = a { v["sides"].as_u64() } else { None }).collect() + } + + #[test] + fn the_counts_stay_within_three_and_eleven() { + assert_eq!(sides_after(5, 1), 6); + assert_eq!(sides_after(5, -1), 4); + assert_eq!(sides_after(5, 100), 11); + assert_eq!(sides_after(5, -100), 3); + assert_eq!(sides_after(3, -1), 3); + assert_eq!(sides_after(11, 1), 11); + // Over 11: unchanged until the drag goes up, which gives 11, then 10. + assert_eq!(sides_after(40, 0), 40); + assert_eq!(sides_after(40, 5), 40); + assert_eq!(sides_after(40, -1), 11); + assert_eq!(sides_after(40, -2), 10); + assert_eq!(sides_after(1000, -100), 3); + } + + #[test] + fn the_longest_drags_stay_within_three_and_eleven() { + assert_eq!(sides_after(5, i64::MAX), 11); + assert_eq!(sides_after(5, i64::MIN), 3); + assert_eq!(sides_after(3, i64::MAX), 11); + assert_eq!(sides_after(11, i64::MAX), 11); + assert_eq!(sides_after(11, i64::MIN), 3); + assert_eq!(sides_after(40, i64::MAX), 40); + assert_eq!(sides_after(40, i64::MIN), 3); + } + + /// A drag far past the document, even one too long to measure, stops at 11 down and 3 up; a + /// pointer position that is not finite keeps the count it had. + #[test] + fn a_huge_or_invalid_drag_stays_within_three_and_eleven() { + let (d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + // At zoom 1 the step count is finite and past i64; at zoom 4 the distance itself is infinite. + for zoom in [1.0, 4.0] { + let c = ToolContext { zoom, ..cx(&d, &s, &p) }; + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let far = |y: f64| Point::new(w.at.x, y); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, far(1e308)))), [11], "zoom {zoom}"); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, far(-1e308)))), [3], "zoom {zoom}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, far(-1e308))), vec![Action::Commit]); + } + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + let shown = w.at + vectorcraft_geom::Vec2::new(0.0, 24.0); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, shown))), [7]); + for bad in [Point::new(f64::NAN, w.at.y), Point::new(w.at.x, f64::INFINITY), Point::new(w.at.x, f64::NEG_INFINITY)] { + assert!(t.pointer(&c, &ev(PointerKind::Drag, bad)).is_empty(), "{bad:?}"); + } + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { p, text } if *p == shown && text == "Sides: 7"))); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, shown)), vec![Action::Commit]); + } + + /// The widget sits 16 px right of the middle of the box's right side, at any zoom; only one + /// whole editable live polygon shows it. + #[test] + fn one_whole_live_polygon_shows_the_widget() { + let (d, id, s) = polygon_doc(6, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, bx) = SideWidget::for_tool(&c).expect("a widget"); + assert_eq!((w.id, w.sides), (id, 6)); + let want = |zoom: f64| Point::new(bx.rect.x1 + 16.0 / zoom, bx.rect.center().y); + assert!(w.at.distance(want(1.0)) < 1e-9, "{w:?} {bx:?}"); + assert!(SideWidget::of(&d, &s, &bx, 4.0).unwrap().at.distance(want(4.0)) < 1e-9); + assert!(over_widget(&c, w.at) && !over_widget(&c, w.at + vectorcraft_geom::Vec2::new(0.0, 8.0))); + // Hidden with the bounding box hidden, with an anchor or segment selected, or with no zoom. + assert!(SideWidget::for_tool(&ToolContext { show_bbox: false, ..cx(&d, &s, &p) }).is_none()); + let mut part = s.clone(); + part.segments.insert(id, Default::default()); + assert!(SideWidget::of(&d, &part, &bx, 1.0).is_none()); + assert!(SideWidget::of(&d, &s, &bx, 0.0).is_none() && SideWidget::of(&d, &s, &bx, f64::NAN).is_none()); + // A locked polygon, two polygons, nothing or a plain path: none. + let mut locked = d.clone(); + locked.node_mut(id).unwrap().locked = true; + assert!(SideWidget::of(&locked, &s, &bx, 1.0).is_none()); + let mut two = d.clone(); + let other = two.alloc_id(); + let mut n = two.node(id).unwrap().clone(); + n.id = other; + let l = two.layers[0].id; + two.insert(Some(l), 0, n).unwrap(); + let mut both = s.clone(); + both.add(other); + assert!(SideWidget::of(&two, &both, &bx, 1.0).is_none()); + assert!(SideWidget::of(&d, &Selection::default(), &bx, 1.0).is_none()); + let (d, rect) = doc_with_rect(); + let mut s = Selection::default(); + s.add(rect); + let bx = OrientedBox::aligned(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + assert!(SideWidget::of(&d, &s, &bx, 1.0).is_none()); + } + + /// With the Selection tool, dragging the widget down adds a side per 12 screen px and up removes + /// them, within 3 to 11, in one undo step with the count shown next to the pointer. + #[test] + fn dragging_the_widget_changes_the_sides() { + let (d, id, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + for zoom in [1.0, 2.0] { + let c = ToolContext { zoom, ..cx(&d, &s, &p) }; + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let at = |px: f64| w.at + vectorcraft_geom::Vec2::new(0.0, px / zoom); + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::ArrowHollow); + assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty()); + // Past the click but short of a step: nothing yet. + assert!(t.pointer(&c, &ev(PointerKind::Drag, at(6.0))).is_empty()); + assert!(t.transforming()); + let a = t.pointer(&c, &ev(PointerKind::Drag, at(12.0))); + assert_eq!(a[0], Action::Begin("Live Shape".into())); + assert_eq!(a[1], Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 6 }))); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Sides: 6"))); + // The same count again sends nothing; far down stops at 11, far up at 3. + assert!(t.pointer(&c, &ev(PointerKind::Drag, at(20.0))).is_empty()); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(500.0)))), [11]); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(-500.0)))), [3]); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at(-500.0))), vec![Action::Commit]); + assert!(!t.busy() && !t.transforming()); + } + // A click sends nothing, and the readout follows Measurement Labels. + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, w.at)).is_empty()); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 13.0))); + let quiet = ToolContext { measurement_labels: false, ..cx(&d, &s, &p) }; + assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + // Back at the start: the release keeps nothing. + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at))), [5]); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, w.at)), vec![Action::Cancel]); + } + + /// On a turned polygon the drag is read along the box's own vertical axis. + #[test] + fn a_turned_polygon_reads_the_drag_along_its_box() { + let xf = Affine::translate((400.0, 400.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2); + let (d, _, s) = polygon_doc(5, xf); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, bx) = SideWidget::for_tool(&c).unwrap(); + let down = bx.to_doc() * Point::new(0.0, 1.0) - bx.to_doc() * Point::ZERO; + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at + down * 25.0))), [7], "{bx:?}"); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at - down * 13.0))), [4]); + } + + /// A double-click on the widget with the Selection tool does nothing: in isolation mode it does + /// not leave isolation, though no art is under the widget. + #[test] + fn a_double_click_on_the_widget_does_nothing() { + let live = LiveShape::Polygon { + radius: 100.0, + sides: 5, + xf: Affine::translate((300.0, 300.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }; + let mut d = Document::new(800.0, 800.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut n = Node::path(id, live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(live)); + } + let group = d.alloc_id(); + d.insert(Some(l), 0, Node::group(group, vec![std::sync::Arc::new(n)])).unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = ToolContext { isolation: Some(group), ..cx(&d, &s, &p) }; + let (w, _) = SideWidget::for_tool(&c).unwrap(); + assert!(vectorcraft_doc::hit::hit_test(&d, w.at, c.hit_options()).is_none()); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::DoubleClick, w.at)).is_empty()); + // Away from the widget and the art, the double-click leaves isolation. + let away = w.at + vectorcraft_geom::Vec2::new(40.0, 0.0); + assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, away)), vec![Action::Exec("object.exitIsolation".into(), json!({}))]); + } + + /// A polygon of more than 11 sides keeps its count on a press and a drag down; the first step + /// up gives 11. + #[test] + fn a_polygon_over_eleven_sides_does_not_jump() { + let (d, _, s) = polygon_doc(40, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 40.0))).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, w.at + vectorcraft_geom::Vec2::new(0.0, 40.0))).is_empty()); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + let a = t.pointer(&c, &ev(PointerKind::Drag, w.at - vectorcraft_geom::Vec2::new(0.0, 12.0))); + assert_eq!(a[0], Action::Begin("Live Shape".into())); + assert_eq!(sides_of(&a), [11]); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Sides: 11"))); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at - vectorcraft_geom::Vec2::new(0.0, 24.0)))), [10]); + } + + /// Escape during a drag puts the count back; the release after it sends nothing. + #[test] + fn escape_cancels_a_side_widget_drag() { + let (d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 30.0))); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert!(t.pointer(&c, &ev(PointerKind::Up, w.at)).is_empty()); + } +} diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index fb7e38bd0f..32502f2607 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -43,10 +43,13 @@ use vectorcraft_text::{FontDb, TextLayout, edit}; use crate::guides::DrawSnap; use crate::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEvent, PointerKind, SurroundingUnit, Tool, ToolContext, ToolKey}; +mod missing; mod plain; mod ports; mod tool; +pub use missing::MISSING_FONT_EDIT; +use missing::PendingEdit; #[cfg(test)] use plain::char_range_to_bytes; use plain::common_affixes; @@ -228,6 +231,8 @@ pub struct TypeTool { stepped: bool, /// The state at the start of each `command.batch` still running, innermost last. batches: Vec, + /// The edit of type set in fonts that aren't available whose question is open ([`missing`]). + pending_edit: Option, cache: Mutex>, /// The other frames' layouts the last overlays drew ([`FrameLayouts`]): each overlays call /// keeps only the frames it draws. @@ -815,18 +820,68 @@ impl TypeTool { /// Start editing the type under `p` with the caret there → the actions (ending the previous /// edit, selecting the type); None when no type is under `p`. A click among the characters - /// edits them, whatever Type Object Selection by Path Only says. + /// edits them, whatever Type Object Selection by Path Only says. When the story of that type is + /// drawn in a font that isn't available as named and is not the story being edited, nothing + /// starts yet: the action asks the UI to open the [`MISSING_FONT_EDIT`] question, and OK starts + /// the edit ([`Self::resume_edit`]). fn edit_at(&mut self, cx: &ToolContext, p: Point) -> Option> { + self.pending_edit = None; let h = hit_test(cx.doc, p, vectorcraft_doc::hit::HitOptions { type_path_only: false, ..cx.hit_options() })?; let Some(NodeKind::Text(t)) = cx.doc.node(h.leaf).map(|n| &n.kind) else { return None }; let lay = self.layout(t); let byte = vectorcraft_text::hit_byte(&lay, t.xf.inverse() * p); + let same_story = self.editing.is_some_and(|e| cx.doc.story_of(e).contains(&h.leaf)); + if !same_story { + let fonts = missing::unavailable_fonts(cx.doc, h.leaf); + if !fonts.0.is_empty() { + let token = next_edit_session(); + self.pending_edit = Some(PendingEdit { token, revision: cx.revision, id: h.leaf, byte, accepted: false }); + self.clicks = (None, 0); + return Some(vec![Action::Dialog(MISSING_FONT_EDIT.into(), missing::question(token, h.leaf, &fonts))]); + } + } + Some(self.begin_edit(cx, h.leaf, byte, p)) + } + + /// End the previous edit and edit type `id` with the caret at `byte` (clicked at `p`), selecting + /// it → the actions. + fn begin_edit(&mut self, cx: &ToolContext, id: NodeId, byte: usize, p: Point) -> Vec { let mut out = self.finish(cx); - self.start_editing(h.leaf, byte); + self.start_editing(id, byte); self.remember(cx); self.clicks = (Some(p), 1); - out.push(Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))); - Some(out) + out.push(Action::Exec("select.set".into(), json!({"ids": [id.0]}))); + out + } + + /// The answer to the [`MISSING_FONT_EDIT`] question whose token is `token`: OK (`ok`) lets the + /// next [`Tool::poll`] start the edit, Cancel forgets it. An answer to another question is + /// ignored. + fn answer_edit(&mut self, token: u64, ok: bool) { + let Some(e) = self.pending_edit.as_mut().filter(|e| e.token == token) else { return }; + if ok { + e.accepted = true; + } else { + self.pending_edit = None; + } + } + + /// Start the edit OK accepted: the caret goes where the type was clicked. Nothing starts when + /// the document changed since the question, or the type is gone. + fn resume_edit(&mut self, cx: &ToolContext) -> Vec { + let Some(e) = self.pending_edit.take_if(|e| e.accepted) else { return vec![] }; + if e.revision != cx.revision { + return vec![]; + } + let Some(t) = Self::text(cx, e.id) else { return vec![] }; + let text = t.plain_text(); + let mut byte = e.byte.min(text.len()); + while !text.is_char_boundary(byte) { + byte -= 1; + } + let out = self.begin_edit(cx, e.id, byte, Point::ZERO); + self.clicks = (None, 0); + out } /// The button released after a press at `start` (new type goes at `at`). While type is being diff --git a/crates/tools/src/text/missing.rs b/crates/tools/src/text/missing.rs new file mode 100644 index 0000000000..7d14d635b4 --- /dev/null +++ b/crates/tools/src/text/missing.rs @@ -0,0 +1,83 @@ +//! Type set in fonts that aren't available as named asks before it is edited: a click or a +//! double-click that would start editing it opens a question ([`MISSING_FONT_EDIT`]) instead, and +//! editing starts at the clicked place only after OK (the tool option `missingFontEdit`). The +//! fonts are those `text.missingFonts` reads, for the story of the type clicked only. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, TextRun}; +use vectorcraft_text::{FontDb, FontMatch}; + +/// The dialog kind of the question, with the fields `token`, `id`, `missing` and `style` (lists of +/// "family style" names) and `more` (how many more fonts the lists leave out). +pub const MISSING_FONT_EDIT: &str = "missingFontEdit"; + +/// The most fonts the question names. +const LISTED: usize = 8; + +/// The longest family or style name checked (bytes), as `text.missingFonts` reads them. +const MAX_NAME: usize = 256; + +/// An edit of type set in fonts that aren't available, waiting for the answer to its question. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct PendingEdit { + /// The question's token, which its answer names. + pub token: u64, + /// The document (its uid) and its revision when the question was asked: an answer to a + /// document since changed starts no editing. + pub revision: (u64, u64), + /// The type clicked, and the caret's byte offset there. + pub id: NodeId, + pub byte: usize, + /// OK was chosen: the next [`crate::Tool::poll`] starts editing. + pub accepted: bool, +} + +/// The fonts (family, style) run `r` is drawn in: its own, or, set in a composite font, those of +/// the parts its characters fall in. An inline graphic and an empty run draw no glyphs. +fn run_fonts(db: &FontDb, r: &TextRun) -> Vec<(String, String)> { + if r.inline.is_some() || r.text.is_empty() { + return vec![]; + } + db.composite_fonts_for(&r.style.font_family, &r.text).unwrap_or_else(|| vec![(r.style.font_family.clone(), r.style.font_style.clone())]) +} + +/// The fonts that the story of type object `id` ([`Document::story_of`]: every frame threaded with +/// it) is drawn in and that aren't available as named, each once, in the order first used, with how +/// they resolve ([`FontMatch::Missing`] or [`FontMatch::Style`]); at most [`LISTED`], with how many +/// more there are. CSS generic families and names longer than 256 bytes are left out, as +/// `text.missingFonts` leaves them out. +pub(super) fn unavailable_fonts(doc: &Document, id: NodeId) -> (Vec<(String, String, FontMatch)>, usize) { + let db = FontDb::global(); + let mut seen = BTreeSet::new(); + let mut listed = Vec::new(); + let mut more = 0; + for frame in doc.story_of(id) { + let Some(NodeKind::Text(t)) = doc.node(frame).map(|n| &n.kind) else { continue }; + for (family, style) in t.runs.iter().flat_map(|r| run_fonts(db, r)) { + if family.trim().is_empty() || vectorcraft_text::is_generic_family(&family) || family.len() > MAX_NAME || style.len() > MAX_NAME { + continue; + } + if !seen.insert((family.clone(), style.clone())) { + continue; + } + let found = db.resolve(&family, &style).map_or(FontMatch::Missing, |(_, m)| m); + if found == FontMatch::Exact { + continue; + } + if listed.len() < LISTED { + listed.push((family, style, found)); + } else { + more += 1; + } + } + } + (listed, more) +} + +/// The question's fields for `fonts` ([`unavailable_fonts`]) and the edit `token` of type `id`. +pub(super) fn question(token: u64, id: NodeId, (fonts, more): &(Vec<(String, String, FontMatch)>, usize)) -> Value { + let names = |m: FontMatch| fonts.iter().filter(|f| f.2 == m).map(|(family, style, _)| format!("{family} {style}")).collect::>(); + json!({"token": token, "id": id.0, "missing": names(FontMatch::Missing), "style": names(FontMatch::Style), "more": more}) +} diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 89a24cc3bf..2542c59f2b 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -1327,6 +1327,7 @@ fn area_type_drag_measure_labels_honor_preference() { #[test] fn layout_cache_follows_fonts_added_later() { + let _inputs = crate::testutil::changing_layout_inputs(); // Other tests can load system fonts; this assertion needs its own process-wide database. #[cfg(not(target_arch = "wasm32"))] if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") { @@ -1542,6 +1543,7 @@ fn selected_type_shows_its_ports_in_each_state() { /// Preferences › Hyphenation › Exceptions change, the selected type is laid out again. #[test] fn the_out_port_follows_the_hyphenation_exceptions() { + let _inputs = crate::testutil::changing_layout_inputs(); struct Clear; impl Drop for Clear { fn drop(&mut self) { @@ -1690,6 +1692,7 @@ const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hund /// overlays as a tool that lays every frame out afresh. #[test] fn type_overlays_keep_the_selected_frames_layouts() { + let _inputs = crate::testutil::steady_layout_inputs(); let (d, ids) = area_frames(&["One", "Two words", "Three words here", OVERFLOWS]); let (mut sel, p) = (Selection::default(), paint()); sel.set(ids.iter().copied()); @@ -1721,6 +1724,7 @@ fn type_overlays_keep_the_selected_frames_layouts() { /// out again on the next frame. #[test] fn type_overlays_keep_a_selected_storys_layouts() { + let _inputs = crate::testutil::steady_layout_inputs(); let (mut d, ids) = area_frames(&["Story one ", "story two ", "story three ", "story four"]); d.text_threads.push(ids.clone()); let (mut sel, p) = (Selection::default(), paint()); @@ -1749,6 +1753,7 @@ fn type_overlays_keep_a_selected_storys_layouts() { /// longer drawn is dropped, and choosing another tool drops them all. #[test] fn type_overlays_lay_out_again_only_the_frames_that_changed() { + let _inputs = crate::testutil::steady_layout_inputs(); let (mut d, ids) = area_frames(&["One", "Two", "Three", OVERFLOWS]); let (mut sel, p) = (Selection::default(), paint()); sel.set(ids.iter().copied()); @@ -1786,6 +1791,7 @@ fn type_overlays_lay_out_again_only_the_frames_that_changed() { /// each call, and draws what laying every frame out afresh draws. #[test] fn type_overlays_keep_at_most_frame_layouts_max() { + let _inputs = crate::testutil::steady_layout_inputs(); let texts = vec!["a "; FRAME_LAYOUTS_MAX + 3]; let (mut d, ids) = area_frames(&texts); d.text_threads.push(ids.clone()); @@ -1806,6 +1812,7 @@ fn type_overlays_keep_at_most_frame_layouts_max() { #[test] fn frame_layouts_follow_fonts_and_hyphenation_exceptions() { + let _inputs = crate::testutil::changing_layout_inputs(); // Other tests can load system fonts; this assertion needs its own process-wide database. #[cfg(not(target_arch = "wasm32"))] if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") { @@ -1848,6 +1855,7 @@ fn frame_layouts_follow_fonts_and_hyphenation_exceptions() { #[test] #[ignore = "timing, run by hand"] fn type_overlays_timing() { + let _inputs = crate::testutil::steady_layout_inputs(); use std::time::Instant; let words = "The quick brown fox jumps over the lazy dog while seven wizards box. ".repeat(6); let texts: Vec = (0..200).map(|i| format!("{i} {words}")).collect(); @@ -2163,3 +2171,157 @@ fn soft_return_in_a_list_item_keeps_tab_within_the_paragraph() { let acts = key(&mut tool, &d, ToolKey::Tab, Mods::default()); assert!(acts.iter().any(|a| matches!(a, Action::Exec(cmd, p) if cmd == "text.setFormat" && p["listLevel"] == 2))); } + +/// A family no computer has. +const NO_SUCH_FAMILY: &str = "Missing Test Family 7258"; + +/// Point type at (x, 100) whose runs are `runs` (text, family, style). +fn add_styled_text(d: &mut Document, x: f64, runs: &[(&str, &str, &str)]) -> NodeId { + let id = d.alloc_id(); + let style = + |family: &str, font_style: &str| CharStyle { size: 20.0, font_family: family.into(), font_style: font_style.into(), ..Default::default() }; + let mut t = TextObject::point(Point::new(x, 100.0), "", style(runs[0].1, runs[0].2)); + t.runs = runs.iter().map(|(text, family, font_style)| TextRun::new(*text, style(family, font_style))).collect(); + d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + id +} + +/// Where the caret before byte `b` of type `id` is drawn (document space). +fn caret_at(c: &ToolContext, id: NodeId, b: usize) -> Point { + let t = TypeTool::text(c, id).unwrap(); + let lay = vectorcraft_text::layout(FontDb::global(), t); + let (a, bb) = vectorcraft_text::caret_position(&lay, b); + let at = t.xf * a.midpoint(bb); + Point::new(at.x + 0.1, at.y) +} + +/// The question a click asked → its token and fields. +fn asked(acts: &[Action]) -> (u64, Value) { + match acts { + [Action::Dialog(kind, p)] if kind == MISSING_FONT_EDIT => (p["token"].as_u64().unwrap(), p.clone()), + _ => panic!("expected only the missing-font question: {acts:?}"), + } +} + +/// A click on type set in a family that isn't available asks first and starts no edit; OK starts +/// it with the caret where the type was clicked, and the font the type names stays as it is. +#[test] +fn a_click_on_type_in_a_missing_font_asks_before_editing() { + let mut d = Document::new(500.0, 500.0); + let id = add_styled_text(&mut d, 100.0, &[("Hello", NO_SUCH_FAMILY, "Regular")]); + let mut tool = TypeTool::new("type"); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, id, 3); + let (token, q) = asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!( + (q["id"].as_u64(), &q["missing"], &q["style"], &q["more"]), + (Some(id.0), &json!([format!("{NO_SUCH_FAMILY} Regular")]), &json!([]), &json!(0)) + ); + assert_eq!(tool.editing, None); + assert!(!tool.waiting()); + // OK: the next poll starts the edit at the clicked character. + tool.set_option("missingFontEdit", &json!({"token": token, "ok": true})); + assert!(tool.waiting()); + let acts = tool.poll(&c, false); + assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); + assert_eq!((tool.editing, tool.caret, tool.anchor), (Some(id), 3, 3)); + assert!(!tool.waiting()); + let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("text") }; + assert_eq!(t.runs[0].style.font_family, NO_SUCH_FAMILY); + // A click within the type being edited moves the caret without asking again. + let at = caret_at(&c, id, 1); + let acts = click(&mut tool, &c, at.x, at.y); + assert!(!acts.iter().any(|a| matches!(a, Action::Dialog(..))), "{acts:?}"); + assert_eq!((tool.editing, tool.caret), (Some(id), 1)); +} + +/// Cancel starts no edit, and the edit in progress on other type goes on; an answer that names +/// another question, or one given to a document changed since, starts nothing either. +#[test] +fn cancel_or_a_stale_answer_starts_no_edit_in_missing_fonts() { + let (mut d, first, mut tool) = editing("First"); + tool.caret = 2; + let other = add_styled_text(&mut d, 300.0, &[("Second", NO_SUCH_FAMILY, "Bold")]); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, other, 2); + let (token, _) = asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!((tool.editing, tool.caret), (Some(first), 2), "the edit in progress goes on while the question is open"); + tool.set_option("missingFontEdit", &json!({"token": token + 1, "ok": true})); + assert!(!tool.waiting(), "another question's answer"); + tool.set_option("missingFontEdit", &json!({"token": token, "ok": false})); + assert!(tool.poll(&c, false).is_empty()); + assert_eq!((tool.editing, tool.caret), (Some(first), 2)); + // OK after the document changed: nothing starts. + let (token, _) = asked(&click(&mut tool, &c, at.x, at.y)); + tool.set_option("missingFontEdit", &json!({"token": token, "ok": true})); + let changed = ToolContext { revision: (0, 1), ..cx(&d, &sel, &p) }; + assert!(tool.poll(&changed, false).is_empty()); + assert_eq!(tool.editing, Some(first)); + assert!(!tool.waiting()); +} + +/// Every new edit of such type asks again, after an earlier OK too, and a style the family lacks +/// asks as a missing family does; type in available fonts is edited at once. +#[test] +fn each_new_edit_of_type_in_unavailable_fonts_asks() { + let mut d = Document::new(500.0, 500.0); + let styled = add_styled_text(&mut d, 100.0, &[("Wide", "Source Sans 3", "Ultra Condensed Oblique 7258")]); + let plain = add_styled_text(&mut d, 300.0, &[("Plain", "Source Sans 3", "Regular")]); + let mut tool = TypeTool::new("type"); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, styled, 1); + let (token, q) = asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!((&q["missing"], &q["style"]), (&json!([]), &json!(["Source Sans 3 Ultra Condensed Oblique 7258"]))); + tool.set_option("missingFontEdit", &json!({"token": token, "ok": true})); + tool.poll(&c, false); + assert_eq!(tool.editing, Some(styled)); + // Other type in an available font is edited at once. + let to = caret_at(&c, plain, 2); + let acts = click(&mut tool, &c, to.x, to.y); + assert!(acts.contains(&Action::Exec("select.set".into(), json!({"ids": [plain.0]}))), "{acts:?}"); + assert_eq!(tool.editing, Some(plain)); + // Back to the first type: a new edit, so the question comes again. + asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!(tool.editing, Some(plain)); +} + +/// The whole story counts: type with one run in a missing font asks even when the click lands in a +/// run in an available font, and the question names each font once. +#[test] +fn a_story_with_one_run_in_a_missing_font_asks() { + let mut d = Document::new(500.0, 500.0); + let id = add_styled_text( + &mut d, + 100.0, + &[("Here ", "Source Sans 3", "Regular"), ("gone ", NO_SUCH_FAMILY, "Regular"), ("again", NO_SUCH_FAMILY, "Regular")], + ); + let mut tool = TypeTool::new("type"); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, id, 1); + let (_, q) = asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!(q["missing"], json!([format!("{NO_SUCH_FAMILY} Regular")])); + assert_eq!(tool.editing, None); +} + +/// Type set in a CSS generic family is edited without a question, and a press dropped while the +/// question is open leaves the edit in progress as it was. +#[test] +fn generic_families_and_a_dropped_press_ask_nothing_more() { + let mut d = Document::new(500.0, 500.0); + let generic = add_styled_text(&mut d, 100.0, &[("Generic", "sans-serif", "Regular")]); + let missing = add_styled_text(&mut d, 300.0, &[("Missing", NO_SUCH_FAMILY, "Regular")]); + let mut tool = TypeTool::new("type"); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, generic, 1); + let acts = click(&mut tool, &c, at.x, at.y); + assert!(acts.contains(&Action::Exec("select.set".into(), json!({"ids": [generic.0]}))), "{acts:?}"); + let to = caret_at(&c, missing, 1); + asked(&tool.pointer(&c, &PointerEvent::new(PointerKind::Down, to.x, to.y))); + assert!(tool.drop_press(&c).is_empty()); + assert_eq!(tool.editing, Some(generic)); +} diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index 2945777610..bd413add45 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -73,8 +73,12 @@ impl Tool for TypeTool { } self.clicks = (None, 0); // A press on other type edits it from there, so a drag selects its text at once, - // as it does in the type being edited. + // as it does in the type being edited. While the question about its fonts is open, + // the press does nothing more, and the edit in progress goes on. if let Some(out) = self.edit_at(cx, ev.pos) { + if self.pending_edit.is_some() { + return out; + } self.selecting = true; self.before_press = Some(before); return out; @@ -472,9 +476,17 @@ impl Tool for TypeTool { } fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.prev_tool = None; + self.pending_edit = None; self.frames.get_mut().unwrap_or_else(|e| e.into_inner()).clear(); self.finish(cx) } + /// OK on the question about type in missing fonts started an edit the next poll begins. + fn waiting(&self) -> bool { + self.pending_edit.as_ref().is_some_and(|e| e.accepted) + } + fn poll(&mut self, cx: &ToolContext, _wait: bool) -> Vec { + self.resume_edit(cx) + } /// Editing ends when a command takes the text out of the selection (Deselect, another object /// picked in the Layers panel) or removes it. After an Undo that takes back a list typed /// characters started, the caret goes on after the characters, and after its Redo the caret @@ -538,9 +550,15 @@ impl Tool for TypeTool { } } /// `select {start, end}` / `selectAll` / `copy` (with `runs` of the selection) / - /// `commitTyping` (the caller commits the engine interaction). + /// `commitTyping` (the caller commits the engine interaction) / `missingFontEdit {token, ok}` + /// (the answer to the question about type in missing fonts; never a saved setting). fn set_option(&mut self, key: &str, v: &Value) { match key { + "missingFontEdit" => { + if let (Some(token), Some(ok)) = (v.get("token").and_then(Value::as_u64), v.get("ok").and_then(Value::as_bool)) { + self.answer_edit(token, ok); + } + } // Transient selection transferred between Type and Eyedropper; never a saved setting. "textSelection" => { if let (Some(id), Some(a), Some(b)) = ( diff --git a/crates/tools/src/touchtype/tests.rs b/crates/tools/src/touchtype/tests.rs index 54c6c86e30..991ab47fdc 100644 --- a/crates/tools/src/touchtype/tests.rs +++ b/crates/tools/src/touchtype/tests.rs @@ -470,6 +470,7 @@ fn the_tool_is_made_by_its_id() { #[test] fn touch_type_rtl_middle_character_can_drag_and_nudge_along_its_line() { + let _inputs = crate::testutil::changing_layout_inputs(); use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font}; // The process-wide database deduplicates the same synthetic face across tests. diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rs index 74cf0b761d..880b6c76b3 100644 --- a/crates/tools/src/xform.rs +++ b/crates/tools/src/xform.rs @@ -18,7 +18,7 @@ use vectorcraft_geom::{BezPath, Point, Rect, Shape}; use crate::{Overlay, Tool}; -pub use artboard::ArtboardTool; +pub use artboard::{ArtboardTool, EDGE_BUTTON_TIP, EDGE_BUTTON_TIP_LOCKED}; pub use eyedropper::EyedropperTool; pub use free::{DistortMode, FreeTransformTool}; pub use gradient::GradientTool; diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index e8cac59c88..fae20e6d4e 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -28,7 +28,8 @@ //! no other artboard). Clicking one adds an empty artboard there (`artboard.new {beside, side}`); //! Alt-clicking duplicates the artboard with its art there (`artboard.duplicate {index, side}`), //! except on a locked artboard, where an Alt-click does nothing. Each is one undo step, and the new -//! artboard becomes the active one. +//! artboard becomes the active one. Resting the pointer on a button shows a tooltip that says what a +//! click does there and, on an unlocked artboard, what an Alt-click does. use serde_json::{Value, json}; use vectorcraft_doc::ArtboardSide; @@ -298,6 +299,10 @@ fn bleed_offset(cx: &ToolContext, rect: Rect, handle: Handle) -> Vec2 { const EDGE_BUTTON_OFFSET: f64 = 18.0; /// The add button's radius in screen pixels: a press this near its center takes it. const EDGE_BUTTON_RADIUS: f64 = 7.0; +/// The add button's tooltip ([`Overlay::HoverText`]), an English UI string the UI translates. +pub const EDGE_BUTTON_TIP: &str = "Click to add an artboard on this side; Alt-click to duplicate this artboard with its art"; +/// The add button's tooltip on a locked artboard, where an Alt-click does nothing. +pub const EDGE_BUTTON_TIP_LOCKED: &str = "Click to add an artboard on this side"; impl ArtboardTool { /// The add buttons on the active artboard's edges, each with its side and center: shown while @@ -657,9 +662,11 @@ impl Tool for ArtboardTool { if self.drag.is_some() { o.extend(self.guides.iter().cloned()); } - // The add buttons: a ring with a plus in it. + // The add buttons: a ring with a plus in it, and a tooltip over the area a press takes. let (radius, arm) = (cx.tol(EDGE_BUTTON_RADIUS), cx.tol(3.5)); + let tip = if ab.locked { EDGE_BUTTON_TIP_LOCKED } else { EDGE_BUTTON_TIP }; for (_, at) in self.edge_buttons(cx) { + o.push(Overlay::HoverText { center: at, radius, text: tip }); let ring: Vec = (0..24).map(|k| at + Vec2::from_angle(f64::from(k) * std::f64::consts::TAU / 24.0) * radius).collect(); let mut path = polygon(&ring, true); for arm in [Vec2::new(arm, 0.0), Vec2::new(0.0, arm)] { diff --git a/crates/tools/src/xform/artboard/tests.rs b/crates/tools/src/xform/artboard/tests.rs index 98410703f6..20c3128176 100644 --- a/crates/tools/src/xform/artboard/tests.rs +++ b/crates/tools/src/xform/artboard/tests.rs @@ -611,6 +611,44 @@ fn add_buttons_hide_with_several_artboards_selected_or_during_a_drag() { assert!(button_sides(&t, &c).is_empty(), "none while an artboard is dragged"); } +/// The tooltips the add buttons carry: each one's center, radius and text. +fn button_tips(t: &ArtboardTool, c: &ToolContext) -> Vec<(Point, f64, &'static str)> { + t.overlays(c) + .into_iter() + .filter_map(|o| if let Overlay::HoverText { center, radius, text } = o { Some((center, radius, text)) } else { None }) + .collect() +} + +#[test] +fn each_add_button_has_a_tooltip_over_the_area_a_press_takes() { + let mut d = two_boards(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let t = ArtboardTool::default(); + let radius = c.tol(EDGE_BUTTON_RADIUS); + let want: Vec<_> = t.edge_buttons(&c).into_iter().map(|(_, at)| (at, radius, EDGE_BUTTON_TIP)).collect(); + assert_eq!(want.len(), 3, "no button and no tooltip on the side without room"); + assert_eq!(button_tips(&t, &c), want); + // The tooltip's disc is the one a press takes. + for (at, r, _) in &want { + assert!(t.edge_button_at(&c, *at + Vec2::new(r * 0.99, 0.0)).is_some()); + assert!(t.edge_button_at(&c, *at + Vec2::new(r * 1.01, 0.0)).is_none()); + } + // None with several artboards selected or during a drag. + let several = ArtboardTool { active: 1, others: vec![0], ..Default::default() }; + assert!(button_tips(&several, &c).is_empty()); + let mut dragging = ArtboardTool::default(); + dragging.pointer(&c, &ev(PointerKind::Down, 700.0, 100.0)); + dragging.pointer(&c, &ev(PointerKind::Drag, 720.0, 100.0)); + assert!(button_tips(&dragging, &c).is_empty(), "none while an artboard is dragged"); + // A locked artboard's buttons tell only what a click does: an Alt-click does nothing there. + d.artboards[0].locked = true; + let c = cx(&d, &s, &p); + let tips = button_tips(&t, &c); + assert_eq!(tips.len(), 3); + assert!(tips.iter().all(|(_, _, text)| *text == EDGE_BUTTON_TIP_LOCKED), "{tips:?}"); +} + #[test] fn an_add_button_adds_an_empty_artboard_and_alt_duplicates_on_that_side() { let d = two_boards(); diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs index 4b9926d616..5d6a18d282 100644 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -1,6 +1,7 @@ //! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller -//! circle's radius, Keep Originals), which previews on the canvas and runs `addon.pathtools.bridge` -//! on OK. +//! circle's radius, or with Constant Gap that radius plus a gap; the reach, unavailable with two +//! circles selected; Keep Originals), which previews on the canvas and runs +//! `addon.pathtools.bridge` on OK. use egui::Ui; use serde_json::{Value, json}; @@ -16,27 +17,61 @@ pub const KIND: &str = "smoothBridge"; /// The radius the command takes (%), and its default. const RADII: std::ops::RangeInclusive = 1.0..=1000.0; const RADIUS: f64 = 100.0; +/// The gap the command takes (pt), and the dialog's first one. +const GAPS: std::ops::RangeInclusive = 0.0..=1000.0; +const GAP: f64 = 4.0; +/// The reach the command takes (pt), and its default. +const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; +const REACH: f64 = 10.0; const LABEL_W: f32 = 60.0; const FIELD_W: f32 = 90.0; /// The dialog's fields to start with: the command's defaults. pub(crate) fn fields() -> Value { - json!({ "radius": RADIUS, "keepOriginals": false }) + json!({ "radius": RADIUS, "constantGap": false, "gap": GAP, "reach": REACH, "keepOriginals": false }) } pub(crate) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Smooth Bridge").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; -/// The command's parameters from the dialog's fields. +/// The command's parameters from the dialog's fields: the radius, or with Constant Gap the gap. fn params(d: &Dialog) -> Value { - json!({ "radius": d.f64("radius", RADIUS), "keepOriginals": d.bool("keepOriginals") }) + let (reach, keep) = (d.f64("reach", REACH), d.bool("keepOriginals")); + if d.bool("constantGap") { + json!({ "gap": d.f64("gap", GAP), "reach": reach, "keepOriginals": keep }) + } else { + json!({ "radius": d.f64("radius", RADIUS), "reach": reach, "keepOriginals": keep }) + } } fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { - widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { - if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) { - d.fields.insert("radius".into(), json!(v)); + let unit = app.session.general_unit(); + form::check(ui, d, "constantGap", tl!("Constant Gap")); + if d.bool("constantGap") { + widgets::label_row(ui, tl!("Gap:"), LABEL_W, |ui| { + form::length_within(ui, d, "gap", unit, FIELD_W, Some(GAPS)); + }); + } else { + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) { + d.fields.insert("radius".into(), json!(v)); + } + }); + } + // The reach applies to three or more circles; two are bridged at any distance. Counted once, + // before a preview replaces the selection with its result. + let many = match d.fields.get("many").and_then(Value::as_bool) { + Some(many) => many, + None => { + let many = app.session.doc().map(|doc| doc.selection.objects.len() > 2).unwrap_or(true); + d.fields.insert("many".into(), json!(many)); + many } + }; + ui.add_enabled_ui(many, |ui| { + widgets::label_row(ui, tl!("Reach:"), LABEL_W, |ui| { + form::length_within(ui, d, "reach", unit, FIELD_W, Some(REACHES)); + }); }); form::check(ui, d, "keepOriginals", tl!("Keep Originals")); form::preview(app, ui, d, "Smooth Bridge", COMMAND, params(d)); @@ -72,9 +107,11 @@ mod tests { menus::invoke(&mut app, &cmd, p); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); - for s in ["Smooth Bridge", "Radius:", "Keep Originals", "Preview"] { + for s in ["Smooth Bridge", "Constant Gap", "Radius:", "Reach:", "Keep Originals", "Preview"] { assert!(shown.contains(s), "{s} in {shown}"); } + assert!(!shown.contains("Gap:"), "{shown}"); + assert!(!app.ui.dialog.as_ref().unwrap().bool("many"), "Reach unavailable for two circles"); let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len(); app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); @@ -89,4 +126,30 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); assert_eq!(count(&app), 3, "the circles and the outline above them"); } + + #[test] + fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // Three circles 4 apart in a row and one far off. + let ids: Vec = [100.0, 124.0, 148.0, 300.0].iter().map(|&x| circle(&mut app, x, 10.0)).collect(); + app.run("select.set", json!({ "ids": ids })).unwrap(); + menus::invoke(&mut app, super::COMMAND, serde_json::Value::Null); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("constantGap".into(), json!(true)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("Gap:") && !shown.contains("Radius:"), "{shown}"); + // A preview leaves two objects selected (one shape and the far circle); Reach stays + // available for the four circles the command still bridges. + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); + assert!(app.ui.dialog.as_ref().unwrap().bool("many"), "Reach available for four circles"); + let p = super::params(app.ui.dialog.as_ref().unwrap()); + assert_eq!(p, json!({"gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); + crate::dialogs::confirm(&mut app).unwrap(); + let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); + } } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a05dcedb38..11c87d07ac 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -164,6 +164,7 @@ impl VectorcraftApp { plugin_runs: Default::default(), placing: Default::default(), trace_runs: Default::default(), + toasts: Default::default(), recovery: Default::default(), host_modifiers: Default::default(), forwarded: Vec::new(), @@ -197,6 +198,7 @@ impl VectorcraftApp { input_frames: vec![], shortcuts_frames: vec![], held_tool: Vec::new(), + hold_keys: Default::default(), synthetic_injected: false, injected_events: vec![], injected_generation: InputGeneration::default(), @@ -638,6 +640,7 @@ impl VectorcraftApp { // After every window this pass may open, and before the palette's field takes the keyboard. panel_docking::close_overlays_for_modal(self, &ctx); palette::show(self, &ctx); + crate::toasts::show(self, &ctx); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); if self.custom_titlebar { diff --git a/crates/ui-egui/src/background.rs b/crates/ui-egui/src/background.rs index b0bdcc6287..f1a3032cf0 100644 --- a/crates/ui-egui/src/background.rs +++ b/crates/ui-egui/src/background.rs @@ -1,7 +1,9 @@ //! Background Save and Background Export (Preferences → File Handling): a save or an export encodes //! and writes a snapshot of the document on a worker thread while editing goes on. The status bar //! shows what is in progress; the result is applied on the UI thread when it arrives (a save marks -//! the document saved as of its snapshot, so edits made meanwhile keep it modified). +//! the document saved as of its snapshot, so edits made meanwhile keep it modified). Exports and +//! saves show in the progress window ([`crate::export_progress`]) with Cancel and Continue in +//! Background. //! //! It needs a thread-safe writer from the host ([`crate::Services::write_shared`], desktop); //! without one (the web, which downloads) the work runs at once, as with the preference off. @@ -44,15 +46,27 @@ struct Task { scope: ScopeHandle, } +/// What a job that shows in the progress window does: its Cancel and Continue in Background act on +/// the jobs of its kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// An export (Background Export): `file.cancelExport`, `file.exportInBackground`. + Export, + /// A save (Background Save): `file.cancelSave`, `file.saveInBackground`. + Save, +} + /// A job in progress. pub struct Job { id: u64, + /// What the job does, for the progress window and its commands. + pub kind: Kind, /// What the status bar and `ui.inspect` show ("Saving Poster.vectorcraft"); empty for work they /// don't show. pub label: String, /// The document the job reads (`DocState::uid`), if any. pub doc: Option, - /// How far an export has got, and its Cancel ([`crate::export_progress`] shows it). + /// How far an export or a save has got, and its Cancel ([`crate::export_progress`] shows it). pub progress: Option>, /// Continue in Background: the progress dialog no longer shows this job. pub hidden: bool, @@ -83,6 +97,9 @@ pub struct Background { next_id: u64, /// Work started while this is set runs at once, whatever the preferences ([`in_foreground`]). foreground: bool, + /// [`crate::state::UiState::status_sets`] right after Cancel Save set its line, or after a save + /// it reached set the line that followed it; `None` before any Cancel Save. + pub(crate) save_cancel_line: Option, } impl Background { @@ -119,18 +136,41 @@ impl Background { /// Cancel every export in progress → how many there were. pub fn cancel_exports(&mut self) -> usize { + self.cancel(Kind::Export) + } + + /// Hide the exports in progress from the progress dialog (they go on) → how many there were. + pub fn hide_exports(&mut self) -> usize { + self.hide(Kind::Export) + } + + /// Cancel every save in progress that the progress window can show → how many there were. + pub fn cancel_saves(&mut self) -> usize { + self.cancel(Kind::Save) + } + + /// Hide the saves in progress from the progress window (they go on) → how many there were. + pub fn hide_saves(&mut self) -> usize { + self.hide(Kind::Save) + } + + /// Is a job of `kind` in progress that can still be canceled? + pub fn running(&self, kind: Kind) -> bool { + self.jobs.iter().any(|j| j.kind == kind && j.progress.is_some() && !j.cancelled()) + } + + fn cancel(&mut self, kind: Kind) -> usize { let mut n = 0; - for p in self.jobs.iter().filter(|j| !j.cancelled()).filter_map(|j| j.progress.as_ref()) { + for p in self.jobs.iter().filter(|j| j.kind == kind && !j.cancelled()).filter_map(|j| j.progress.as_ref()) { p.cancel(); n += 1; } n } - /// Hide the exports in progress from the progress dialog (they go on) → how many there were. - pub fn hide_exports(&mut self) -> usize { + fn hide(&mut self, kind: Kind) -> usize { let mut n = 0; - for j in self.jobs.iter_mut().filter(|j| j.progress.is_some() && !j.hidden && !j.cancelled()) { + for j in self.jobs.iter_mut().filter(|j| j.kind == kind && j.progress.is_some() && !j.hidden && !j.cancelled()) { j.hidden = true; n += 1; } @@ -163,6 +203,34 @@ pub fn run_with_progress( progress: Option>, work: impl FnOnce(Writer) -> Result + Send + 'static, then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, +) -> Result { + start(app, enabled, label, doc, progress, Kind::Export, work, then) +} + +/// [`run_with_progress`] for a save of document `doc`: the progress window shows it as a save, and +/// its Cancel is `file.cancelSave`. +pub fn run_saving( + app: &mut VectorcraftApp, + enabled: bool, + label: String, + doc: u64, + progress: Arc, + work: impl FnOnce(Writer) -> Result + Send + 'static, + then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, +) -> Result { + start(app, enabled, label, Some(doc), Some(progress), Kind::Save, work, then) +} + +#[allow(clippy::too_many_arguments)] +fn start( + app: &mut VectorcraftApp, + enabled: bool, + label: String, + doc: Option, + progress: Option>, + kind: Kind, + work: impl FnOnce(Writer) -> Result + Send + 'static, + then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, ) -> Result { let mut work: Work = Box::new(work); let shared = app.services.write_shared.clone().filter(|_| enabled && !app.background.foreground && app.services.download.is_none()); @@ -174,7 +242,8 @@ pub fn run_with_progress( let (sets, status) = (app.ui.status_sets, if label.is_empty() { String::new() } else { format!("{label}…") }); let bg = &mut app.background; bg.next_id += 1; - bg.jobs.push(Job { id, label: label.clone(), doc, progress, hidden: false, sets, line: status.clone(), then: Box::new(then) }); + let line = status.clone(); + bg.jobs.push(Job { id, kind, label: label.clone(), doc, progress, hidden: false, sets, line, then: Box::new(then) }); if label.is_empty() { return Ok(json!({ "background": true })); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ef7ef0ba78..02833a7c09 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -52,7 +52,7 @@ use fill::{fill_view, polygon_area}; #[cfg(test)] use grid::ruler_rects; use grid::{LineLook, PIXEL_GRID, PIXEL_GRID_ZOOM, checker, clip_segment, grid, ruler_input, rulers, rulers_hidden, textured_quad, view_bounds}; -pub(crate) use grid::{RulerScale, checker_texture, ruler_label, ruler_origin_dragging}; +pub(crate) use grid::{RulerScale, checker_texture, checker_tile, ruler_label, ruler_origin_dragging}; #[cfg(test)] pub(crate) use grid::{TRANSPARENCY_GRID, vertical_label_height}; use home::home; @@ -63,7 +63,9 @@ use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; pub use overlays::SharedPaths; #[cfg(test)] use overlays::selected_anchor; -use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; +use overlays::{ + HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, overlay_hover_text, selection_overlay, +}; pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; @@ -424,6 +426,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs), &mut shared_paths); app.canvas.shared_paths = shared_paths; crate::panels::tabs::paint_stop_guide(app, &painter, &xf); + overlay_hover_text(ui, &xf, &overlays, ui.data(|d| d.get_temp::(drag_id())).is_some()); if !revolve_edit { shaper_widget_overlay(app, &painter, &xf); crate::panels::three_d::paint_graphic_handles(app, &painter, &xf); diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index bdda812306..36188617ac 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -16,6 +16,8 @@ pub(super) struct HoverContext { pub(super) center: Point, pub(super) zoom: f64, pub(super) rotation: f64, + /// A pen turning in place changes a Bristle tip even when its pointer stays still. + pub(super) pen: Option, /// The active document's id and revision (which moves with every edit, undo and selection /// change). pub(super) doc: Option<(u64, u64)>, diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 001b2e31f7..5d533f7eaf 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -11,20 +11,31 @@ pub(crate) fn checker_texture( setup: &vectorcraft_doc::DocSetup, display: Option<&vectorcraft_color::cms::display::DisplayTransform>, ) -> (egui::TextureHandle, f32) { - let colors = setup.grid_colors.map(|c| crate::display_profile::color32(display, crate::panels::c32(&c))); // A tile of its own with a display profile, so a preview drawn in sRGB beside the canvas // doesn't make the canvas's tile again each frame. let id = egui::Id::unique("transparency-grid-tile").with(display.is_some()); + (checker_tile(ctx, setup.grid_colors, display, id), setup.grid_size.cell()) +} + +/// The transparency grid's 2 × 2-cell tile in the colors `grid_colors` (the first in the top-left +/// and bottom-right cells), converted into the display profile `display` when there is one, and +/// cached under `id` until the colors change. +pub(crate) fn checker_tile( + ctx: &egui::Context, + grid_colors: [vectorcraft_color::Color; 2], + display: Option<&vectorcraft_color::cms::display::DisplayTransform>, + id: egui::Id, +) -> egui::TextureHandle { + let colors = grid_colors.map(|c| crate::display_profile::color32(display, crate::panels::c32(&c))); let cached = ctx.data(|d| d.get_temp::<([Color32; 2], egui::TextureHandle)>(id)).filter(|(c, _)| *c == colors); - let tex = cached.map(|(_, t)| t).unwrap_or_else(|| { + cached.map(|(_, t)| t).unwrap_or_else(|| { let [a, b] = colors; let img = egui::ColorImage::new([2, 2], vec![a, b, b, a]); let opts = egui::TextureOptions { wrap_mode: egui::TextureWrapMode::Repeat, ..egui::TextureOptions::NEAREST }; let t = ctx.load_texture(TRANSPARENCY_GRID, img, opts); ctx.data_mut(|d| d.insert_temp(id, (colors, t.clone()))); t - }); - (tex, setup.grid_size.cell()) + }) } /// Name of the transparency grid's texture. diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index d811ad3bac..9467596cf7 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -12,6 +12,9 @@ use super::{Color32, Drag, Mods, Point, PointerEvent, PointerKind, Pos2, Shape, /// Dispatch canvas pointer, keyboard and drop events through the active document view. pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { + if let Some(feed) = app.services.stylus.as_ref() { + feed.bind_repaint(ui.ctx()); + } // A modal dialog takes the canvas's presses, finger taps, long touches and view navigation, from the frame it opens. let modal = crate::panel_docking::modal_open(app, ui.ctx()); let (pointer, m, space, hover) = wheel_view(app, ui, resp, rect, modal); @@ -53,7 +56,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo }); // What a hover means besides where the pointer is on screen: the tool, the canvas, the view // (scrolled, zoomed or turned by the wheel, a gesture, keys or a command) and the document and - // selection as they are (another tab, an edit, an undo). Under a still pointer, a tool switched + // selection as they are (another tab, an edit, an undo), and the pen's orientation. Under a still pointer, a tool switched // to is hovered at once, and when the rest changes, a tool that asks for it // ([`Session::tool_wants_rehover`]) is hovered again where the pointer is. let context = HoverContext { @@ -62,13 +65,14 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo center: v.center, zoom: v.zoom, rotation: v.rotation, + pen: pen_pose(app, &xf), doc: app.session.active().map(|st| (st.uid, st.revision)), }; - let (tool_switched, context_changed) = ui.data_mut(|d| { + let (tool_switched, context_changed, pen_changed) = ui.data_mut(|d| { let id = egui::Id::unique("canvas-hover-context"); let prev = d.get_temp::(id); d.insert_temp(id, context); - prev.map_or((false, false), |prev| (prev.tool != context.tool, prev != context)) + prev.map_or((false, false, false), |prev| (prev.tool != context.tool, prev != context, prev.pen != context.pen)) }); if app.ui.screen_mode == 3 && matches!(drag, None | Some(Drag::Present | Drag::Gesture)) { @@ -137,7 +141,12 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo } else if let Some(p) = hover_tool // A press on an artboard's name starts no drag: the moves while it is held are not hover. && !(pointer.primary_down() && ui.data(|d| d.get_temp::<(usize, bool)>(name_press_id()).is_some())) - && (pointer.is_moving() || mods_changed || !was_over || tool_switched || (context_changed && app.session.tool_wants_rehover())) + && (pointer.is_moving() + || mods_changed + || !was_over + || tool_switched + || (context_changed && app.session.tool_wants_rehover()) + || (pen_changed && context.tool == "paintbrush")) { let ev = PointerEvent { kind: PointerKind::Move, @@ -145,7 +154,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo mods: mods(m, space), backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), pressure: 1.0, - pen: None, + pen: pen_pose(app, &xf), }; dispatch(app, &ev, view); } diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 613b0fae9c..de05367568 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -255,6 +255,13 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: p.circle_filled(c, r, if w.area { color } else { Color32::WHITE }); p.circle_stroke(c, r, Stroke::new(1.0, color)); } + // A live polygon's side widget: a diamond beside the middle of the box's right side, drawn + // only while the box is drawn (the box hides during a turn and during a drag of the widget). + if !drawing_boxed && let Some(w) = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &b, xf.zoom) { + let (c, r) = (xf.to_screen(w.at), vectorcraft_tools::sidewidget::RADIUS_PX); + let diamond = vec![c + vec2(0.0, -r), c + vec2(r, 0.0), c + vec2(0.0, r), c + vec2(-r, 0.0)]; + p.add(Shape::convex_polygon(diamond, Color32::WHITE, Stroke::new(1.0, color))); + } } // Pie widgets (Selection tool, with View › Show Bounding Box, on live ellipses): each joined // by a line to the outline's point at its angle. They stay while one is dragged. @@ -596,6 +603,29 @@ pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: p.circle_stroke(c, 8.0, Stroke::new(2.0, t.accent)); } } + // Shown as a tooltip by `overlay_hover_text`; nothing is drawn. + Overlay::HoverText { .. } => {} + } + } +} + +/// The tooltips of the tool's [`Overlay::HoverText`] regions. Each region is a hover-only widget +/// over the canvas, which keeps the clicks and drags; while the pointer rests inside a region's +/// disc, egui shows its text, translated, after its usual tooltip delay. No tooltip shows during a +/// canvas drag (`dragging`) or while a pointer button is down. +pub(super) fn overlay_hover_text(ui: &egui::Ui, xf: &Xf, overlays: &[Overlay], dragging: bool) { + let pressed = ui.input(|i| i.pointer.any_down()); + for (i, o) in overlays.iter().enumerate() { + let Overlay::HoverText { center, radius, text } = o else { continue }; + let c = xf.to_screen(*center); + let r = (*radius * xf.zoom) as f32; + if !(r.is_finite() && r > 0.0 && c.is_finite()) { + continue; + } + let id = egui::Id::unique("canvas-hover-text").with(i); + let resp = ui.interact(egui::Rect::from_center_size(c, vec2(2.0 * r, 2.0 * r)), id, egui::Sense::hover()); + if !dragging && !pressed && resp.hover_pos().is_some_and(|p| p.distance(c) <= r) { + resp.on_hover_text(crate::i18n::t(text)); } } } diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 6b1d8ac3f2..cef27dab18 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -10,12 +10,12 @@ use std::collections::HashMap; use std::sync::Arc; use super::grid::LineLook; -use super::outline::{c32, node_outline, stroke_path, too_many_anchors}; +use super::outline::{c32, node_outline, to_screen_path, too_many_anchors}; use super::view::fit_zoom; use super::{ - Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key, - dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers, - shows_artboards, textured_quad, vec2, view_rects, + Affine, BezPath, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, + cache_key, dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, + rulers, shows_artboards, textured_quad, vec2, view_rects, }; use crate::doc_windows::Win; use crate::thumb_worker::ThumbWorker; @@ -46,6 +46,29 @@ pub struct Panes { /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and /// center the fit gave. fits: HashMap, + /// By slot: the outlines of the selected objects the pane drew last, and what they show. + outlines: HashMap, + /// How many times a pane's outlines were made. + outlines_made: u64, +} + +/// A pane's selected-object outlines as screen shapes, and the document revision, document, +/// selection and screen mapping they were made for. +struct Outlines { + revision: u64, + /// A weak reference to the document: while it exists, no other document can take the + /// allocation's address. + doc: std::sync::Weak, + selection: Vec, + affine: [f64; 6], + shapes: Vec, +} + +impl Outlines { + /// Whether these outlines show `st`'s selection through the screen mapping `affine`. + fn shows(&self, st: &vectorcraft_engine::DocState, affine: &[f64; 6]) -> bool { + self.revision == st.revision && self.doc.ptr_eq(&Arc::downgrade(&st.doc)) && self.affine == *affine && self.selection == st.selection.objects + } } impl Panes { @@ -56,6 +79,7 @@ impl Panes { self.last.clear(); self.last_slots.clear(); self.fits.clear(); + self.outlines.clear(); } /// Upload `img`, the render `key` describes, for `slot`. @@ -311,6 +335,9 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.clear(); } app.canvas.panes.last.clear(); + // Only the floating windows draw panes now. + let floating = &app.ui.floating; + app.canvas.panes.outlines.retain(|(u, n), _| floating.iter().any(|w| w.uid == *u && w.view == *n)); app.canvas.panes.last_slots.clear(); return false; } @@ -326,6 +353,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); + app.canvas.panes.outlines.retain(|s, _| live.contains(s)); // A window that moved to another pane fits it, and so does a window whose pane changed place or // size because a window opened, closed, floated or docked, or because the panes came back from // one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its @@ -563,7 +591,9 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo guides_of(app, st, (&painter, &xf, &t), rect); } if app.ui.view.edges { - selected_objects(st, &painter, &xf); + selected_objects(&mut app.canvas.panes, slot, st, &painter, &xf); + } else { + app.canvas.panes.outlines.remove(&slot); } if app.ui.view.rulers && app.ui.screen_mode < 3 { rulers(ui, full, &xf, None, RulerScale::document(app.session.general_unit(), st.doc.ruler_origin_for(v.artboard)), &t); @@ -581,23 +611,45 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo resp.contains_pointer() && ui.input(|inp| inp.pointer.any_pressed()) } -/// The outlines of the objects selected in `st`, in their layers' colors; their bounds when they -/// have too many points to outline. -fn selected_objects(st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) { +/// Draw the outlines of the objects selected in `st` ([`outline_shapes`]) in `slot`'s pane, from +/// the outlines `panes` kept for the slot while they show the same revision, document, selection +/// and screen mapping, and made again otherwise. +fn selected_objects(panes: &mut Panes, slot: Slot, st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) { + let affine = xf.affine().as_coeffs(); + if !panes.outlines.get(&slot).is_some_and(|o| o.shows(st, &affine)) { + let shapes = outline_shapes(st, xf); + let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: st.selection.objects.clone(), affine, shapes }; + panes.outlines.insert(slot, kept); + panes.outlines_made += 1; + } + for shape in panes.outlines.get(&slot).map_or(&[][..], |o| &o.shapes) { + painter.add(shape.clone()); + } +} + +/// The outlines of the objects selected in `st` as lines on the screen through `xf`, in their +/// layers' colors; their bounds when they have too many points to outline. +fn outline_shapes(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec { + let mut shapes = vec![]; + if st.selection.objects.is_empty() { + return shapes; + } let symbols = st.doc.symbol_boxes(); let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> = st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect(); let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id))); + let mut stroke = |bp: &BezPath, s: Stroke| shapes.extend(to_screen_path(bp, xf).into_iter().map(|line| egui::Shape::line(line, s))); if too_many_anchors(nodes.iter().map(|(_, n)| *n)) { let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b)); if let (Some(b), Some((id, _))) = (bounds, nodes.first()) { - stroke_path(painter, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, color(*id)); + stroke(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id)); } - return; + return shapes; } for (id, n) in nodes { - stroke_path(painter, &node_outline(n, &symbols), xf, color(id)); + stroke(&node_outline(n, &symbols), color(id)); } + shapes } #[cfg(test)] diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 6c7a8cf755..15e5e138d3 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -875,6 +875,149 @@ fn other_panes_draw_their_guides_and_selected_objects() { assert_ne!(layer, Color32::TRANSPARENT); } +/// The selected objects' outlines as the panes made them on every frame before they kept them, +/// to hold the kept outlines against. +fn outlines_made_each_frame(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec { + let mut shapes = vec![]; + let symbols = st.doc.symbol_boxes(); + let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> = + st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect(); + let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id))); + let mut stroke_path = |bp: &BezPath, s: Stroke| { + for line in to_screen_path(bp, xf) { + shapes.push(Shape::line(line, s)); + } + }; + if too_many_anchors(nodes.iter().map(|(_, n)| *n)) { + let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b)); + if let (Some(b), Some((id, _))) = (bounds, nodes.first()) { + stroke_path(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id)); + } + return shapes; + } + for (id, n) in nodes { + stroke_path(&node_outline(n, &symbols), color(id)); + } + shapes +} + +/// The first document's pane in a tiled pair: the outlines it keeps, after checking that they +/// equal the outlines made afresh through its view and that the frame `drawn` holds them in order. +fn kept_outlines<'a>(app: &'a VectorcraftApp, ctx: &egui::Context, drawn: &[Shape]) -> &'a [Shape] { + let pane = panes(app).1[0]; + let xf = Xf::new(view_rects(app, pane, ctx.pixels_per_point()).1, &app.views[0]); + let slot = (app.session.documents()[0].uid, 1); + let kept = &app.canvas.panes.outlines.get(&slot).expect("the pane keeps its outlines").shapes; + assert_eq!(kept, &outlines_made_each_frame(&app.session.documents()[0], &xf), "the kept outlines are the ones made afresh"); + assert!(kept.is_empty() || drawn.windows(kept.len()).any(|w| w == kept.as_slice()), "the pane draws the kept outlines"); + kept +} + +/// Run `cmd` on the first document of a tiled pair, then make the second current again. +fn in_first(app: &mut VectorcraftApp, cmd: &str, args: serde_json::Value) -> serde_json::Value { + app.run("document.activate", json!({"index": 0})).unwrap(); + let out = app.session.execute(cmd, &args).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + out +} + +#[test] +fn kept_outlines_do_not_show_for_a_new_document_that_takes_a_freed_documents_address() { + let affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let st = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None); + let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: vec![], affine, shapes: vec![] }; + assert!(kept.shows(&st, &affine), "the outlines show the document they were made for"); + let freed = Arc::as_ptr(&st.doc); + drop(st); + let mut reused = false; + for _ in 0..64 { + let other = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None); + reused |= Arc::as_ptr(&other.doc) == freed; + assert!(!kept.shows(&other, &affine), "a different document with the same revision, selection and mapping is not the one shown"); + } + assert!(!reused, "the weak reference keeps the freed document's address from being taken"); +} + +#[test] +fn other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = egui::Context::default(); + let rect = in_first(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80}))["id"].clone(); + let ellipse = in_first(&mut app, "shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60}))["id"].clone(); + in_first(&mut app, "select.set", json!({"ids": [rect, ellipse]})); + frame(&mut app, &ctx, vec![]); + let drawn = frame(&mut app, &ctx, vec![]); + assert!(kept_outlines(&app, &ctx, &drawn).len() >= 2, "the rectangle and the ellipse are outlined"); + let made = app.canvas.panes.outlines_made; + let drawn = frame(&mut app, &ctx, vec![]); + kept_outlines(&app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made, "an unchanged frame draws the kept outlines"); + let changed = |app: &mut VectorcraftApp, what: &str| { + let made = app.canvas.panes.outlines_made; + let drawn = frame(app, &ctx, vec![]); + kept_outlines(app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made + 1, "{what} makes the outlines again, once"); + let drawn = frame(app, &ctx, vec![]); + kept_outlines(app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made + 1, "the frame after {what} draws the kept outlines"); + }; + in_first(&mut app, "select.set", json!({"ids": [ellipse]})); + changed(&mut app, "a new selection"); + in_first(&mut app, "object.move", json!({"dx": 30, "dy": -10})); + changed(&mut app, "a move"); + let layer = app.session.documents()[0].doc.layers[0].id.0; + in_first(&mut app, "layer.setProps", json!({"id": layer, "color": "#20a040"})); + changed(&mut app, "a new layer color"); + app.views[0].center.x += 25.0; + changed(&mut app, "a pan"); + app.views[0].zoom *= 1.5; + app.views[0].rotation = 20.0; + changed(&mut app, "a zoom and a turn"); + app.ui.view.edges = false; + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "with Edges off no outlines are kept"); + app.ui.view.edges = true; + changed(&mut app, "Edges on again"); + in_first(&mut app, "select.none", json!({})); + changed(&mut app, "an empty selection"); + let drawn = frame(&mut app, &ctx, vec![]); + assert!(kept_outlines(&app, &ctx, &drawn).is_empty()); + // 30,000 rectangles have more points than the outlines are made for: the pane keeps the bounds. + let st = &app.session.documents()[0]; + let rect = st.doc.node(vectorcraft_doc::NodeId(rect.as_u64().unwrap())).cloned().unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for _ in 0..30_000 { + let mut n = rect.clone(); + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n)?; + } + Ok(()) + }) + .unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + changed(&mut app, "selecting more points than are outlined"); + let drawn = frame(&mut app, &ctx, vec![]); + assert_eq!(kept_outlines(&app, &ctx, &drawn).len(), 1, "one rectangle around the bounds"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "Consolidate All Windows forgets the outlines"); + // Panes that stop showing before their render arrives keep no outlines either. + app.run("window.arrange.tile", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.canvas.panes.outlines.len(), 1); + app.ui.tiled = false; + app.canvas.panes.shown.clear(); + app.canvas.panes.last.clear(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "no pane shows, so no outlines are kept"); +} + #[test] fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() { let mut app = app_with(2); @@ -1209,3 +1352,82 @@ fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_con assert!(differs(want, blend(s, front_paper)), "the front document's paper blends to another color"); assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color"); } + +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a pane's selected-object outlines with every object of a document selected: 2,000 and +/// 20,000 rectangles, 20,000 ellipses, and 150,000 rectangles (more points than are outlined, so +/// the pane draws their bounds). Each frame is a whole egui pass that draws the outlines and the +/// tessellation of what it drew, made afresh on every frame ([`outlines_made_each_frame`]) or +/// drawn from the kept outlines ([`selected_objects`]). The sides alternate, and the median time +/// per frame of 7 runs is printed. +/// Run with `cargo test --release -p vectorcraft-ui-egui --lib pane_outlines_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; performance depends on machine load"] +fn pane_outlines_timing() { + const FRAMES: u32 = 20; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{clock} per frame, median of 7 runs of {FRAMES} frames"); + for (count, shape) in [(2_000, "shape.rectangle"), (20_000, "shape.rectangle"), (20_000, "shape.ellipse"), (150_000, "shape.rectangle")] { + let mut app = app_with(1); + let id = app.run(shape, json!({"x": 20, "y": 20, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for _ in 1..count { + let mut n = node.clone(); + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n)?; + } + Ok(()) + }) + .unwrap(); + app.run("select.all", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.selection.objects.len(), count); + let ctx = egui::Context::default(); + let area = egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0)); + let xf = Xf { rect: area, zoom: 4.0, center: Point::new(50.0, 40.0), rot: 0.0 }; + let mut kept = Panes::default(); + let slot = (st.uid, 1); + let mut pass = |fresh: bool| { + let raw = egui::RawInput { screen_rect: Some(area), ..Default::default() }; + let out = ctx.run_ui(raw, |ui| { + let painter = ui.painter_at(area); + if fresh { + for s in outlines_made_each_frame(st, &xf) { + painter.add(s); + } + } else { + selected_objects(&mut kept, slot, st, &painter, &xf); + } + }); + ctx.tessellate(out.shapes, out.pixels_per_point).len() + }; + assert_eq!(pass(true), pass(false), "both sides draw as much"); + let mut time = |fresh: bool| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..FRAMES { + pass(fresh); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(FRAMES) / 1e6 + }; + let (mut fresh, mut cached) = (vec![], vec![]); + for _ in 0..7 { + fresh.push(time(true)); + cached.push(time(false)); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let shapes = kept.outlines.get(&slot).map_or(0, |o| o.shapes.len()); + eprintln!("{count} x {shape} ({shapes} lines drawn)"); + eprintln!(" made every frame: {:>9.3} ms {fresh:.3?}", median(&mut fresh)); + eprintln!(" kept: {:>9.3} ms {cached:.3?}", median(&mut cached)); + } +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cea61e42bb..3adab31ffa 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1165,6 +1165,90 @@ fn the_artboard_tool_names_its_active_artboard_once() { assert!((active[0].1 - other[0].1).abs() < 2.0, "on the artboard's top edge like the other name: {active:?} vs {other:?}"); } +/// The texts one headless 800 × 600 canvas frame at `time` seconds draws, tooltips included. +fn texts_at(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) -> Vec { + fn collect(shape: &Shape, texts: &mut Vec) { + match shape { + Shape::Text(t) => texts.push(t.galley.text().to_string()), + Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, texts)), + _ => {} + } + } + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut texts = vec![]; + out.shapes.iter().for_each(|s| collect(&s.shape, &mut texts)); + texts +} + +/// The Artboard tool's add buttons: resting the pointer on one shows its tooltip after egui's +/// tooltip delay, over the disc a press takes and not beside it. No tooltip shows while a drag +/// is under way, or once the button is gone. +#[test] +fn an_artboard_add_button_shows_its_tooltip_while_the_pointer_rests_on_it() { + use egui::Event; + let tip = vectorcraft_tools::xform::EDGE_BUTTON_TIP; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + texts_at(&mut app, &ctx, 0.0, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + // The bottom button: the one below the artboard. + let regions: Vec<(Pos2, f32)> = app + .session + .overlays(app.view_info()) + .into_iter() + .filter_map(|o| match o { + Overlay::HoverText { center, radius, text } if text == tip => Some((xf.to_screen(center), (radius * xf.zoom) as f32)), + _ => None, + }) + .collect(); + assert_eq!(regions.len(), 4, "one tooltip for each add button"); + let (at, r) = regions.iter().copied().max_by(|a, b| a.0.y.total_cmp(&b.0.y)).unwrap(); + assert!((r - 7.0).abs() < 1e-3, "the disc a press takes: {r}"); + let shown = |texts: &[String]| texts.iter().any(|s| s == tip); + // Resting inside the disc: nothing at first, the tooltip after the delay. + assert!(!shown(&texts_at(&mut app, &ctx, 1.0, vec![Event::PointerMoved(at + vec2(r - 1.0, 0.0))]))); + assert!(!shown(&texts_at(&mut app, &ctx, 1.05, vec![])), "egui's tooltip delay first"); + let mut seen = false; + for k in 1..=20 { + seen |= shown(&texts_at(&mut app, &ctx, 1.05 + 0.1 * f64::from(k), vec![])); + } + assert!(seen, "the tooltip shows while the pointer rests on the button"); + // Just outside the disc, inside the square around it: no tooltip. + let mut t = 4.0; + texts_at(&mut app, &ctx, t, vec![Event::PointerMoved(at + vec2(r - 1.0, r - 1.0))]); + for _ in 0..20 { + t += 0.1; + assert!(!shown(&texts_at(&mut app, &ctx, t, vec![])), "beside the button"); + } + // A middle-button drag that starts on the button pans the view with the pointer, so the pointer + // stays on the button: no tooltip while it lasts. + let middle = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() }; + texts_at(&mut app, &ctx, t, vec![Event::PointerMoved(at)]); + t += 0.1; + texts_at(&mut app, &ctx, t, vec![middle(at, true)]); + let to = at + vec2(30.0, 0.0); + for _ in 0..20 { + t += 0.1; + assert!(!shown(&texts_at(&mut app, &ctx, t, vec![Event::PointerMoved(to)])), "during a drag"); + } + texts_at(&mut app, &ctx, t, vec![middle(to, false)]); + // With an artboard below, there is no room for the bottom button, and its tooltip goes with it. + let r0 = app.session.active().unwrap().doc.artboards[0].rect; + app.session.execute("artboard.new", &json!({"beside": 0, "side": "bottom"})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[0].rect, r0); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let below = xf.to_screen(vectorcraft_geom::Point::new(r0.center().x, r0.y1)) + vec2(0.0, 18.0); + texts_at(&mut app, &ctx, t, vec![Event::PointerMoved(below)]); + for _ in 0..20 { + t += 0.1; + assert!(!shown(&texts_at(&mut app, &ctx, t, vec![])), "no tooltip where no button shows"); + } +} + #[test] fn shift_clicking_canvas_artboard_label_toggles_multi_selection() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -6653,6 +6737,48 @@ fn a_selected_ellipse_shows_its_pie_widgets() { assert_eq!(widgets(&mut app), 0, "no bounding box, no widgets"); } +/// A selected live polygon shows its side widget, a white diamond beside its box, with the +/// Selection tool and the shape tools while the bounding box shows, and hides with the box while +/// the polygon is moved. +#[test] +fn a_selected_polygon_shows_its_side_widget() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.polygon", &json!({"cx": 200, "cy": 150, "radius": 60, "sides": 5})).unwrap(); + let ctx = egui::Context::default(); + // A white diamond as wide and tall as the widget. + let size = 2.0 * vectorcraft_tools::sidewidget::RADIUS_PX; + let diamond = |ps: &egui::epaint::PathShape| { + let span = |f: fn(&egui::Pos2) -> f32| { + let v: Vec = ps.points.iter().map(f).collect(); + v.iter().copied().fold(f32::MIN, f32::max) - v.iter().copied().fold(f32::MAX, f32::min) + }; + ps.closed && ps.points.len() == 4 && ps.fill == Color32::WHITE && (span(|p| p.x) - size).abs() < 0.01 && (span(|p| p.y) - size).abs() < 0.01 + }; + let widgets = |app: &mut VectorcraftApp| shapes(app, &ctx).iter().filter(|s| matches!(s, Shape::Path(ps) if diamond(ps))).count(); + app.select_tool("selection"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("polygon"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("directSelection"); + assert_eq!(widgets(&mut app), 0); + app.select_tool("lineSegment"); + assert_eq!(widgets(&mut app), 0); + app.select_tool("selection"); + app.run("view.boundingBox", json!({})).unwrap(); + assert_eq!(widgets(&mut app), 0, "no bounding box, no widget"); + app.run("view.boundingBox", json!({})).unwrap(); + // A move of the polygon hides the box, and the widget with it, until the release. + let view = app.view_info(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 150.0), view).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 150.0), view).unwrap(); + assert_eq!(widgets(&mut app), 0, "hidden while the polygon moves"); + app.session.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 150.0), view).unwrap(); + assert_eq!(widgets(&mut app), 1, "back after the release"); + app.session.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + assert_eq!(widgets(&mut app), 0, "an ellipse has none"); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] @@ -8889,6 +9015,11 @@ fn retype_all_of_a_copied_type(ime: bool) { frame(&mut app, vec![button(at, pressed, Modifiers::NONE)]); } frame(&mut app, vec![]); + // Without Georgia on this computer, the Type tool asks first; OK starts the edit. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::confirm::MISSING_FONT_EDIT) { + crate::dialogs::confirm(&mut app).unwrap(); + frame(&mut app, vec![]); + } assert_eq!(app.session.tool_options()["editing"], json!(copy)); // 3. Select all of its text and type over it. frame(&mut app, vec![key(Key::A, true, Modifiers::COMMAND)]); @@ -8976,6 +9107,65 @@ fn double_clicking_type_with_the_direct_selection_tool_puts_the_caret_there() { assert!(!app.session.tool_wants_text()); } +/// Double-clicking type set in a family that isn't available asks before the Type tool edits it: +/// Cancel leaves the document, its undo history and the selection as they were, with nothing +/// edited; OK puts the caret where the type was clicked, and typing edits the type, which keeps +/// the family it names. +#[test] +fn double_clicking_type_in_a_missing_font_asks_before_editing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let params = json!({"x": 100, "y": 150, "text": "Hello world", "size": 24, "font": "Missing Test Family 7258"}); + let id = app.session.execute("text.create", ¶ms).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + let timed = |app: &mut VectorcraftApp, time: f64, events: Vec| { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + timed(&mut app, 0.0, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let node = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let b = node(&app).geometric_bounds().unwrap(); + let at = xf.to_screen(b.center()); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let double_click = |app: &mut VectorcraftApp, time: f64| { + timed(app, time, vec![egui::Event::PointerMoved(at), button(true), button(false), button(true), button(false)]); + timed(app, time + 0.1, vec![]); + }; + let asking = |app: &VectorcraftApp| app.ui.dialog.as_ref().filter(|d| d.kind == crate::dialogs::confirm::MISSING_FONT_EDIT).cloned(); + double_click(&mut app, 1.0); + let d = asking(&app).expect("the question about the missing font"); + assert!(d.str("detail").contains("Missing Test Family 7258 Regular"), "{}", d.str("detail")); + assert_eq!(app.session.tool_options()["editing"], json!(null)); + // Cancel: nothing is edited, and the document, its undo history and the selection stay. + let (before, undo, selected) = + (node(&app), app.session.doc().unwrap().history.undo.len(), app.session.active().unwrap().selection.objects.clone()); + crate::dialogs::cancel(&mut app); + timed(&mut app, 1.5, vec![]); + assert_eq!(app.session.tool_options()["editing"], json!(null)); + assert!(!app.session.tool_wants_text()); + assert_eq!(node(&app), before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert_eq!(app.session.active().unwrap().selection.objects, selected); + // A new double-click asks again; OK edits with the caret where the type was clicked. + double_click(&mut app, 3.0); + assert!(asking(&app).is_some(), "asked again"); + crate::dialogs::confirm(&mut app).unwrap(); + timed(&mut app, 3.5, vec![]); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options(); + assert_eq!(o["editing"], json!(id)); + let caret = o["caret"].as_u64().unwrap(); + assert!((1..11).contains(&caret), "caret {caret}"); + app.session.tool_text("X", app.view_info()).unwrap(); + let NodeKind::Text(t) = &node(&app).kind else { panic!("not text") }; + assert_eq!(t.plain_text().find('X'), Some(caret as usize), "{}", t.plain_text()); + assert!(t.runs.iter().all(|r| r.style.font_family == "Missing Test Family 7258")); +} + #[test] fn escape_while_editing_in_isolation_returns_to_selection_tool_and_keeps_isolation_until_second_escape() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -11292,6 +11482,46 @@ fn the_tip_brings_back_the_perspective_grid_tool_without_showing_the_grid() { assert!(!visible(&app), "the grid stays hidden"); } +/// The native pen feed's barrel rotation reaches the Paintbrush during canvas hover, before any +/// stroke begins. Turning the pen or replacing it with a mouse updates a still pointer too. +#[test] +fn bristle_pen_tip_reaches_the_canvas_before_a_press() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let feed = StylusFeed::default(); + app.services.stylus = Some(feed.clone()); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.session.execute("brush.setCurrent", &json!({"name": "Bristle Flat Fan"})).unwrap(); + app.select_tool("paintbrush"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_rect.unwrap().center(); + let tip = |app: &mut VectorcraftApp| { + app.session.overlays(app.view_info()).into_iter().find_map(|o| match o { + vectorcraft_tools::Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. } => Some(path.bounding_box()), + _ => None, + }) + }; + feed.set_sample(Some(crate::stylus::PenSample { + pressure: 0.0, + pose: PenPose { rotation: Some(0.0), ..Default::default() }, + ..Default::default() + })); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let horizontal = tip(&mut app).expect("hovering pen shows its brush tip"); + assert!(horizontal.width() > horizontal.height() * 2.0, "{horizontal:?}"); + feed.set_sample(Some(crate::stylus::PenSample { + pressure: 0.0, + pose: PenPose { rotation: Some(90.0), ..Default::default() }, + ..Default::default() + })); + frame(&mut app, &ctx, vec![]); + let vertical = tip(&mut app).expect("turning a still pen turns its tip"); + assert!(vertical.height() > vertical.width() * 2.0, "{vertical:?}"); + feed.set(None); + frame(&mut app, &ctx, vec![]); + assert!(tip(&mut app).is_none(), "a mouse clears a still pen's tip"); +} + /// #764: the pen's tilt and barrel rotation in the host's feed reach the Paintbrush's points, /// the tilt turned onto the page when the view is rotated; a mouse's points carry neither. #[test] diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 2c7ae8ed20..e68f821261 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -78,6 +78,48 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon } } +/// The selected paths' eligible corners, as document lengths, beside the anchor controls. +/// Explicit partial selections with no corners contribute no target (unlike `picked`'s fallback). +fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, reserve: f32) { + let Some(st) = app.session.active() else { return }; + let mut items = Vec::new(); + let mut radius: Option = None; + let mut mixed = false; + for &id in &st.selection.objects { + let Some(lc) = st.doc.node(id).and_then(vectorcraft_doc::LiveCorners::of) else { continue }; + let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); + if corners.is_empty() { + continue; + } + for &k in &corners { + // Keep absolute requested radii, even when their drawing is fitted smaller. Relative + // storage is a fraction, but the field and setLiveShape both consume document lengths. + let value = if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }; + if let Some(first) = radius { + mixed |= (first - value).abs() >= 1e-9; + } else { + radius = Some(value); + } + } + items.push(json!({"id": id, "corners": corners})); + } + if items.is_empty() { + return; + } + let label = tl!("Corner Radius:"); + let text = egui::RichText::new(label).size(12.0).color(t.text); + if ui.available_width() < row_width(ui, &[widgets::text_width(ui, text.clone()), INLINE_FIELD_WIDTH]) + reserve { + return; + } + widgets::field_label(ui, text); + let shown = if mixed { None } else { radius }; + let unit = app.session.general_unit(); + if let Some(radius) = widgets::num_field_named(ui, "cb-corner-radius", Some(label), shown, unit, INLINE_FIELD_WIDTH) { + // App::run reports any command failure in the status bar, as the other inline fields do. + app.run("object.setLiveShape", json!({"items": items, "radius": radius.max(0.0)})).ok(); + } +} + /// The id of the Control bar's isolation button. pub(super) const ISOLATION_BUTTON: &str = "cb-isolation"; @@ -1035,6 +1077,8 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, } if anchors != AnchorControls::None && group_on(app, "anchors") { anchor_buttons(app, ui, anchors); + let reserve = transform_reserve(app, ui, !sel.is_empty()); + corner_radius(app, ui, t, reserve); } let object_options = group_on(app, "objectOptions"); if object_options { diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 45cd600771..7c39666f78 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -401,7 +401,7 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { let more = busy.len() - 1; (if more > 0 { format!("{label}… (+{more})") } else { format!("{label}…") }, &[][..]) } else { - (crate::i18n::msg(&app.ui.status), status_notes(&app.ui)) + (status_message(app), status_notes(&app.ui)) }; if !message.is_empty() { let rect = egui::Rect::from_min_max(egui::pos2((area.left() + 18.0).min(right), area.top()), egui::pos2(right, area.bottom())); @@ -409,6 +409,19 @@ pub(super) fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { } } +/// The status message in the interface language. While it is the error of the last script run +/// and that error's message is text the script supplied, that text is shown as it is and only the +/// words around it are translated. +pub(crate) fn status_message(app: &VectorcraftApp) -> String { + let status = app.ui.status.as_str(); + if let Some((before, kept, after)) = app.session.script_authored_failure() + && status.strip_prefix(before.as_str()).and_then(|rest| rest.strip_suffix(after.as_str())) == Some(kept) + { + return crate::i18n::msg_keeping(&before, kept, &after); + } + crate::i18n::msg(status) +} + /// Most notes the status message's hover and access information list. const MAX_LISTED_NOTES: usize = 30; diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 09d31f1a5f..4c9506b13c 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -899,6 +899,59 @@ fn the_message_of_an_open_with_several_notes_lists_them_on_hover() { assert_eq!(hovered.iter().filter(|t| t.text.starts_with("Opened")).count(), 1, "no tooltip: {hovered:?}"); } +/// The status message of a failed script run shows text the script threw as it is, even when it +/// reads like one of the app's own errors, and translates the words around it; the app's own error +/// is translated. Both a run that ends in one call and a run the frames take to its end show it. +#[test] +fn german_script_status_preserves_authored_error_and_translates_native_error() { + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let failed = |app: &mut crate::VectorcraftApp, source: &str, frames: bool| { + app.session.script_frames = frames; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})); + if frames { + assert_eq!(r.map(|v| v["running"].clone()), Ok(json!(true)), "{source}"); + for _ in 0..1_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(app); + } + } else { + assert!(r.is_err(), "{source}"); + } + assert!(!app.session.script_running()); + super::status_bar::status_message(app) + }; + let long = "invalid array length ".repeat(120); + for frames in [false, true] { + let shown = failed(&mut app, "throw new Error('invalid array length')", frames); + assert_eq!(shown, "t.js: Zeile 1, Spalte 1: Error: invalid array length (ausgelöst)"); + let shown = failed(&mut app, "throw 'invalid array length'", frames); + assert_eq!(shown, "t.js: Zeile 1, Spalte 1: invalid array length (ausgelöst)"); + let shown = failed(&mut app, "new Array(-1)", frames); + assert!(shown.starts_with("t.js: Zeile 1, Spalte 1: ") && shown.contains("ungültige Array-Länge"), "{shown}"); + for text in ["", "invalid array length\nsecond line", "{name}: {e}", "t.js: line 1, column 1: invalid array length (thrown)", long.as_str()] { + let source = format!("throw {}", serde_json::to_string(text).unwrap()); + assert_eq!(failed(&mut app, &source, frames), format!("t.js: Zeile 1, Spalte 1: {text} (ausgelöst)"), "{text}"); + } + } + // Another message, even one spelled like the script's text, is translated as before. + failed(&mut app, "throw 'invalid array length'", false); + app.ui.status = "invalid array length".to_string(); + assert_eq!(super::status_bar::status_message(&app), "ungültige Array-Länge"); + // A change of language while the message stays keeps the script's text. + failed(&mut app, "throw new Error('invalid array length')", false); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered")); + assert_eq!(super::status_bar::status_message(&app), "t.js\u{a0}: ligne 1, colonne 1\u{a0}: Error: invalid array length (levée)"); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(super::status_bar::status_message(&app), app.ui.status); + // After a run that completes, the message is an ordinary one. + app.session.script_frames = false; + app.run("script.run", json!({"source": "1", "name": "t.js"})).unwrap(); + assert_eq!(app.session.script_authored_failure(), None); +} + /// The message of an open that starts with a line about its linked files lists the open's notes on /// hover and for screen readers, in a wide and in a narrow window. A later message leaves the list /// out. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 15f456d51f..b5b829ebbf 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1609,6 +1609,8 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) let names = crate::dialogs::field_names(d).join(", "); return err(format!("the `{}` dialog has no field `{f}`; its fields: {names}", d.kind)); } + // Create Object Mosaic converts New Size against the selected image's size as it is now. + crate::dialogs::object_mosaic::refresh(app); // In order: a field that sets others (an export preset) goes before the fields after it. // A field that fails leaves the dialog as it was before the request. let before = app.ui.dialog.clone(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 53e808afa8..37781291ec 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -15,6 +15,7 @@ pub mod action_select_object; pub mod action_set_options; pub mod action_stop; pub mod artboard_options; +pub mod attributes_panel_options; pub mod blend_options; mod brush_art_options; pub mod brush_delete; @@ -48,6 +49,7 @@ mod export_for_screens; pub mod eyedropper; pub mod file_info; pub mod find_links; +pub mod find_replace; pub mod flare_options; pub mod flatten; pub mod flattener_presets; @@ -81,6 +83,7 @@ pub mod new_color_group; mod new_document; pub mod new_swatch; pub mod new_text_style; +pub mod object_mosaic; pub mod objects_on_path_options; pub mod office_export; pub mod package; @@ -344,6 +347,7 @@ registry! { ReplaceFiles: [confirm::REPLACE_FILES] => confirm::REPLACE_FILES_SPEC, ResetPreferences: [confirm::RESET_PREFS] => confirm::RESET_PREFS_SPEC, ResetActions: [confirm::RESET_ACTIONS] => confirm::RESET_ACTIONS_SPEC, + MissingFontEdit: [confirm::MISSING_FONT_EDIT] => confirm::MISSING_FONT_EDIT_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC, GraphData: [graph_data::KIND] => graph_data::SPEC, @@ -399,6 +403,7 @@ registry! { MissingLinks: [missing_links::KIND] => missing_links::SPEC, MissingFonts: [missing_fonts::KIND] => missing_fonts::SPEC, FindLinks: [find_links::KIND] => find_links::SPEC, + FindReplace: [find_replace::KIND] => find_replace::SPEC, TextImport: [text_import::KIND] => text_import::SPEC, PdfPresets: [pdf_presets::KIND] => pdf_presets::SPEC, PdfPreset: [save_pdf::PRESET_KIND] => save_pdf::PRESET_SPEC, @@ -444,6 +449,7 @@ registry! { ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, + ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, SmartPunctuation: [smart_punctuation::KIND] => smart_punctuation::SPEC, @@ -474,6 +480,7 @@ registry! { LayerOptions: [layer_options::KIND] => layer_options::SPEC, LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, NavigatorPanelOptions: [navigator_panel_options::KIND] => navigator_panel_options::SPEC, + AttributesPanelOptions: [attributes_panel_options::KIND] => attributes_panel_options::SPEC, PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, PixelSnapOptions: [pixel_snap_options::KIND] => pixel_snap_options::SPEC, RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, @@ -542,10 +549,10 @@ fn hidden_controls(d: &Dialog) -> &'static [&'static str] { Some(DialogKind::Preferences) => &["__category", "__search", "__smartGuides", "__snapToGrid", "__taskBar"], // The section shown, the sheet the preview shows and the preset name being typed. Some(DialogKind::Print | DialogKind::PrintPreset) => &["__savePresetAs", "__section", "__sheet"], - // The section shown, All or a range of artboards, the two password checkboxes and the - // preset name being typed. + // The section shown, All or a range of artboards, the bleed link, the two password + // checkboxes and the preset name being typed. Some(DialogKind::SavePdf | DialogKind::PdfPreset) => { - &["__allArtboards", "__requireOpenPassword", "__restrictPermissions", "__savePresetAs", "__section"] + &["__allArtboards", "__bleedLinked", "__requireOpenPassword", "__restrictPermissions", "__savePresetAs", "__section"] } // The selected rows and Randomize's seed. Some(DialogKind::Recolor) => &["__seed", "__sel"], @@ -624,12 +631,21 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == new_document::KIND || new_document::popup_open(d) { new_document::note_set(d, &field); } + // Create Object Mosaic's Resize Using Percentages shows the new size the other way, as its checkbox does. + if d.kind == object_mosaic::KIND && field == "percentages" { + object_mosaic::set_percentages(d, &value); + return; + } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); + let mosaic = (d.kind == object_mosaic::KIND).then(|| field.clone()); let graph = (d.kind == graph_data::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { dxf_options::note_set(d, &field); } + if let Some(field) = mosaic { + object_mosaic::note_set(d, &field); + } if let Some(field) = graph { graph_data::note_set(d, &field); } @@ -680,8 +696,9 @@ pub(crate) fn parent(d: &Dialog) -> Option { /// `flattenerPreset`, which drops the Custom… options), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in /// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor -/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. A value -/// Composite Fonts' Show Sample can't take is refused. +/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. Save +/// PDF's bleed link links the bleed as its button does. A value Composite Fonts' Show Sample or +/// Save PDF's bleed link can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); @@ -693,6 +710,9 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { return composite_fonts::field_set(d, field); } + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == save_pdf::KIND || d.kind == save_pdf::PRESET_KIND) { + return save_pdf::field_set(d, field); + } if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { eps_options::field_set(d, field); return Ok(()); @@ -728,6 +748,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == safe_mode::STOPPED { safe_mode::cancel_stopped(app); } + if d.kind == confirm::MISSING_FONT_EDIT { + confirm::answer_missing_font_edit(app, &d, false); + } // The growth question's Cancel button is its Stop button. if d.kind == script_run::GROWTH_KIND { app.session.script_request_stop(); diff --git a/crates/ui-egui/src/dialogs/attributes_panel_options.rs b/crates/ui-egui/src/dialogs/attributes_panel_options.rs new file mode 100644 index 0000000000..2a5a7356ff --- /dev/null +++ b/crates/ui-egui/src/dialogs/attributes_panel_options.rs @@ -0,0 +1,82 @@ +//! Attributes panel › Panel Options…: how many recent URLs the panel's URL menu lists. +//! +//! Field: `count` (1–30). OK runs `ui.attributesPanelOptions` with it (kept with the UI state). + +use serde_json::{Value, json}; + +use super::DialogSpec; +use super::swatch_options::{grid, label}; +use crate::panels::attributes::DEFAULT_RECENT_URLS; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the Attributes Panel Options. +pub const KIND: &str = "attributesPanelOptions"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Attributes Panel Options").into(), body, confirm, min_width: 280.0, ..DialogSpec::FORM }; + +/// `ui.attributesPanelOptions` without options: open the dialog on the panel's options. +pub fn open(app: &mut VectorcraftApp) -> Result { + let count = app.ui.attributes_panel.shown(); + app.ui.dialog = Some(Dialog::new(KIND, json!({ "count": count }))); + Ok(Value::Null) +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + grid(ui, |ui| { + label(ui, tl!("Number of Recent URLs:")); + let v = d.f64("count", f64::from(DEFAULT_RECENT_URLS)); + let max = vectorcraft_engine::cmd::RECENT_URLS as f64; + if let Some(v) = widgets::range_field(ui, "attributes-recent-urls", v, 1.0..=max, "", 0, 60.0) { + d.fields.insert("count".into(), json!(v)); + } + ui.end_row(); + }); + false +} + +/// OK: set the count; a count that is refused leaves the dialog open. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = json!({ "count": d.fields.get("count").cloned().unwrap_or(Value::Null) }); + let r = app.run("ui.attributesPanelOptions", params)?; + app.ui.dialog = None; + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// The dialog opens on the panel's count (10 by default), OK sets it, kept with the UI state, + /// and a count out of range is refused, leaving the dialog open and the count as it was. + #[test] + fn panel_options_set_the_recent_url_count() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.attributesPanelOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.f64("count", 0.0)), (KIND, 10.0)); + // Drawn headlessly in the shared frame. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let set = |app: &mut VectorcraftApp, count: Value| { + app.ui.dialog.as_mut().unwrap().fields.insert("count".into(), count); + super::super::confirm(app) + }; + assert_eq!(set(&mut app, json!(25.0)).unwrap(), json!({"count": 25})); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.attributes_panel.recent_urls, 25); + app.run("ui.attributesPanelOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("count", 0.0), 25.0, "opens on the current count"); + assert!(set(&mut app, json!(31)).is_err()); + assert!(app.ui.dialog.is_some() && app.ui.attributes_panel.recent_urls == 25, "a refused count changes nothing"); + // Cancel closes the dialog without applying what was typed. + app.ui.dialog.as_mut().unwrap().fields.insert("count".into(), json!(3)); + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.attributes_panel.recent_urls, 25); + } +} diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 15b28c2d27..b4fd6f037e 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -156,6 +156,47 @@ fn reset_actions(app: &mut VectorcraftApp, d: &Dialog) -> Result app.run(crate::panels::actions::RESET, json!({ "mode": mode })) } +/// The dialog kind of the question a click or double-click asks before it edits type set in fonts +/// that aren't available as named ([`ask_missing_font_edit`]). Fields: `message`, `detail`, +/// `__token` (the Type tool's edit, which the answer names). +pub const MISSING_FONT_EDIT: &str = vectorcraft_tools::text::MISSING_FONT_EDIT; + +pub(super) const MISSING_FONT_EDIT_SPEC: DialogSpec = DialogSpec { confirm: edit_in_missing_fonts, ..SPEC }; + +/// Ask whether to edit type whose story is drawn in fonts that aren't available, which the Type +/// tool names in `p` (`token`, `missing` and `style`: "family style" names, `more`: how many more +/// there are). The detail names each font (family and style, the family's own names, which are +/// not translated). OK starts the edit where the type was clicked; Cancel and Escape start nothing. +pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { + let names = |k: &str| p.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::>(); + let mut fonts = names("missing"); + fonts.extend(names("style")); + if p.get("more").and_then(Value::as_u64).is_some_and(|n| n > 0) { + fonts.push("…".to_string()); + } + let detail = format!("{}\n{}", fonts.join(", "), tl!("These fonts aren't available. Their text shows in another font.")); + let message = tl!("Edit type set in fonts that aren't available?"); + let fields = json!({"message": message, "detail": detail, "__token": p.get("token")}); + app.ui.dialog = Some(Dialog::new(MISSING_FONT_EDIT, fields)); +} + +/// OK on [`ask_missing_font_edit`]: closes, then the Type tool starts the edit. +fn edit_in_missing_fonts(app: &mut VectorcraftApp, d: &Dialog) -> Result { + app.ui.dialog = None; + answer_missing_font_edit(app, d, true); + Ok(Value::Null) +} + +/// Give the Type tool the answer to [`ask_missing_font_edit`]'s question `d`: with `ok` the edit +/// starts at once; without, the tool forgets it. +pub(super) fn answer_missing_font_edit(app: &mut VectorcraftApp, d: &Dialog, ok: bool) { + app.session.set_tool_option("missingFontEdit", &json!({"token": d.fields.get("__token"), "ok": ok})); + if ok { + let r = app.session.tool_poll(app.view_info(), false); + crate::canvas::apply_requests(app, r); + } +} + /// Most messages kept for later while a dialog is open ([`tell`]). const MAX_WAITING: usize = 16; diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 187e36e6b0..78cc370cfc 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -7,13 +7,16 @@ //! tab's `colorMode`, `convertColors`, `rgbProfile` and `cmykProfile` (null: the working space). //! OK runs `document.setup` with them: one undo step. When the Color tab changed something, OK runs //! `document.setup`, `edit.assignProfile` and `file.documentColorMode` in one `command.batch`, -//! and the document's changes are still one undo step. On an error the dialog stays open. +//! and the document's changes are still one undo step. On an error the dialog stays open. When OK +//! raises the bleed on a side, the status bar counts the objects that reach an artboard's trim edge +//! on a side OK raised but stop short of the new bleed there. use serde_json::{Map, Value, json}; use vectorcraft_color::cms::ProfileKind; -use vectorcraft_doc::setup::{GRID_COLOR_PRESETS, LANGUAGES}; +use vectorcraft_doc::setup::{GRID_COLOR_PRESETS, LANGUAGES, bleed_in_range}; use vectorcraft_doc::{ColorMode, GridSize, Quotes, Unit}; use vectorcraft_engine::cmd::colormgmt::doc_profiles; +use vectorcraft_engine::cmd::fileio::pdf; use super::{DialogSpec, form}; use crate::state::Dialog; @@ -102,6 +105,7 @@ fn color_commands(app: &VectorcraftApp, d: &Dialog) -> Result, String fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let params: Map = d.fields.iter().filter(|(k, _)| !UI_ONLY.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); let color = color_commands(app, d)?; + let before = app.session.active().map(|st| st.doc.setup.bleed); let r = if color.is_empty() { app.run("document.setup", Value::Object(params)) } else { @@ -110,10 +114,24 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }; if r.is_ok() { app.ui.dialog = None; + if let Some(note) = before.and_then(|b| short_of_bleed_note(app, b)) { + app.status(note); + } } r } +/// The status note after OK raised the bleed on a side from `before`: how many objects reach an +/// artboard's trim edge on a side whose bleed grew but stop short of the new bleed there. `None` +/// when no side grew or no object stops short. +fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option { + let doc = &app.session.active()?.doc; + // In the range the PDF pages keep the document's bleed to. + let (bleed, before) = (bleed_in_range(doc.setup.bleed), bleed_in_range(before)); + let raised: [f64; 4] = std::array::from_fn(|i| if bleed[i] > before[i] { bleed[i] } else { 0.0 }); + pdf::short_of_bleed_warning(pdf::short_of_bleed(doc, raised, None, false)) +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let tab = TABS.iter().position(|t| *t == d.str("tab")).unwrap_or(0); if let Some(i) = widgets::tab_bar(ui, &TABS, tab) { @@ -180,15 +198,65 @@ fn grid_color_box_id(index: usize) -> egui::Id { egui::Id::unique(("grid-color-box", index)) } -/// The grid colors' hex codes that Document Setup `d` holds now (empty strings for entries that are -/// not strings). -fn grid_colors(d: &Dialog) -> Vec { - d.fields.get("gridColors").and_then(Value::as_array).map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()).unwrap_or_default() +/// The size of the Transparency tab's grid preview, in points. +const GRID_PREVIEW: egui::Vec2 = egui::vec2(112.0, 72.0); + +/// The grid size and the two colors the grid preview shows for the dialog's fields `fields`, read +/// as `document.setup` reads them (a preset name or two colors): a field that is missing or not a +/// valid value shows as `setup`, the document's setting. +fn preview_grid(fields: &Map, setup: &vectorcraft_doc::DocSetup) -> (GridSize, [vectorcraft_color::Color; 2]) { + let size = fields.get("gridSize").and_then(Value::as_str).and_then(GridSize::parse).unwrap_or(setup.grid_size); + (size, grid_colors(fields, setup)) +} + +/// The two grid colors the dialog's fields `fields` hold, read as `document.setup` reads +/// `gridColors` (a preset name, in any letter case, or two colors): a field that is missing or not +/// a valid value gives `setup`'s colors, the document's setting. +fn grid_colors(fields: &Map, setup: &vectorcraft_doc::DocSetup) -> [vectorcraft_color::Color; 2] { + let colors = match fields.get("gridColors") { + Some(Value::String(name)) => GRID_COLOR_PRESETS.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, pair)| *pair), + Some(Value::Array(a)) if a.len() == 2 => a.iter().map(vectorcraft_engine::cmd::color_value).collect::>>().map(|c| [c[0], c[1]]), + _ => None, + }; + colors.unwrap_or(setup.grid_colors) +} + +/// The checkered preview of the grid the dialog's Grid Size and Grid Colors hold, drawn with the +/// canvas's transparency grid tile and cell size: the first color in the top-left cell. It goes +/// beside the rows that start at `top`, against the right edge, or below them when they leave no +/// room. It shows the grid whatever Simulate Colored Paper and View › Show Transparency Grid are, +/// and changes nothing in the document. +fn grid_preview(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog, top: f32) { + let t = Tokens::get(ui.ctx()); + let fallback = vectorcraft_doc::DocSetup::default(); + let setup = app.session.active().map_or(&fallback, |st| &st.doc.setup); + let (size, colors) = preview_grid(&d.fields, setup); + let right = ui.max_rect().right(); + let rect = if ui.min_rect().right() + 16.0 + GRID_PREVIEW.x <= right { + egui::Rect::from_min_size(egui::pos2(right - GRID_PREVIEW.x, top), GRID_PREVIEW) + } else { + ui.add_space(4.0); + ui.allocate_exact_size(GRID_PREVIEW, egui::Sense::hover()).0 + }; + let resp = ui.interact(rect, grid_preview_id(), egui::Sense::hover()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Transparency Grid"))); + let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); + let id = egui::Id::unique("document-setup-grid-preview").with(display.is_some()); + let tile = crate::canvas::checker_tile(ui.ctx(), colors, display.as_deref(), id); + let uv = egui::Rect::from_min_max(egui::Pos2::ZERO, (rect.size() / (2.0 * size.cell())).to_pos2()); + ui.painter().image(tile.id(), rect, uv, egui::Color32::WHITE); + ui.painter().rect_stroke(rect, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Outside); +} + +/// The id of the Transparency tab's grid preview. +fn grid_preview_id() -> egui::Id { + egui::Id::unique("grid-preview") } fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); widgets::subheader(ui, tl!("Transparency Grid")); + let top = ui.cursor().top(); let sizes: Vec<(&str, &str)> = GridSize::ALL.iter().map(|g| (g.id(), g.label())).collect(); choice(ui, d, "gridSize", tl!("Grid Size:"), &sizes); // A preset name in the fields (any case, as `document.setup` takes it) becomes the preset's two @@ -198,10 +266,15 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { { d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); } - let colors = grid_colors(d); + // The pair the field holds, or the document's pair when it holds no two colors, so each box and + // hex field shows a color and the picker and hex fields set an entry of a two-color list. + let fallback = vectorcraft_doc::DocSetup::default(); + let setup = app.session.active().map_or(&fallback, |st| &st.doc.setup); + let pair = |d: &Dialog| -> Vec { grid_colors(&d.fields, setup).iter().map(vectorcraft_color::Color::to_hex).collect() }; + let colors = pair(d); let preset = GRID_COLOR_PRESETS .iter() - .find(|(_, pair)| colors.len() == 2 && colors.iter().zip(pair).all(|(h, c)| h.eq_ignore_ascii_case(&c.to_hex()))) + .find(|(_, pair)| colors.iter().zip(pair).all(|(h, c)| h.eq_ignore_ascii_case(&c.to_hex()))) .map_or("Custom", |(n, _)| n); let names: Vec<&str> = GRID_COLOR_PRESETS.iter().map(|(n, _)| *n).chain(["Custom"]).collect(); widgets::label_row(ui, tl!("Grid Colors:"), LABEL, |ui| { @@ -211,10 +284,10 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { }); // The two colours (the first is also the paper colour): editing either makes them Custom. A // click on a color's box, or Space or Enter with the keyboard on it, opens the Color Picker on - // that color (white when its hex is not a color), and the picker's OK sets that color. The - // picker opens after the row, on the color Document Setup holds then: a press on a box ends a - // hex field's editing in the same frame, and that field's edit is the color the picker opens on. - // A hex field's edit replaces its own color in the pair Document Setup holds when it commits. + // that color, and the picker's OK sets that color. The picker opens after the row, on the color + // Document Setup holds then: a press on a box ends a hex field's editing in the same frame, and + // that field's edit is the color the picker opens on. A hex field's edit replaces its own color + // in the pair Document Setup holds when it commits. let mut pick = None; widgets::label_row(ui, "", LABEL, |ui| { for i in 0..2 { @@ -242,16 +315,23 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.painter().rect_stroke(chip.expand(2.0), 3.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside); } if let Some(c) = widgets::hex_field_named(ui, ("grid-color", i), Some(&name), hex).and_then(|h| vectorcraft_color::Color::from_hex(&h)) { - let mut v = grid_colors(d); - v.resize(2, "#ffffff".into()); + let mut v = pair(d); v[i] = c.to_hex(); d.fields.insert("gridColors".into(), json!(v)); } ui.add_space(10.0); } }); + grid_preview(app, ui, d, top); if let Some(i) = pick { - let c = grid_colors(d).get(i).and_then(|h| vectorcraft_color::Color::from_hex(h.trim_start_matches('#'))); + // A field that is not two colors becomes the pair the boxes show, so the picker's OK has an + // entry to set. + let v = pair(d); + let entries = d.fields.get("gridColors").and_then(Value::as_array); + if !entries.is_some_and(|a| a.len() == 2 && a.iter().all(|c| vectorcraft_engine::cmd::color_value(c).is_some())) { + d.fields.insert("gridColors".into(), json!(v)); + } + let c = v.get(i).and_then(|h| vectorcraft_color::Color::from_hex(h.trim_start_matches('#'))); *d = super::color_picker::over_list_entry(d, "gridColors", i, c.unwrap_or(vectorcraft_color::Color::WHITE)); } ui.add_space(4.0); @@ -467,6 +547,51 @@ mod tests { assert!(app.ui.dialog.is_some()); } + /// OK with a larger bleed shows how many objects reach the trim edge but stop short of it; a + /// smaller bleed, or a larger one that no object falls short of, shows no such note. + #[test] + fn ok_with_a_larger_bleed_counts_the_art_short_of_it() { + let short = |app: &VectorcraftApp| app.ui.status.contains("short of the bleed"); + let ok_with_sides = |app: &mut VectorcraftApp, bleed: [f64; 4]| { + app.status(""); + app.run("file.documentSetup", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("bleed".into(), json!(bleed)); + crate::dialogs::confirm(app).unwrap(); + }; + let ok_with_bleed = |app: &mut VectorcraftApp, bleed: f64| ok_with_sides(app, [bleed; 4]); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + // A background that fills a 4 pt bleed on the top, left and right. + let id = app.run("shape.rectangle", json!({"x": -4, "y": -4, "width": 208, "height": 50})).unwrap()["id"].clone(); + app.run("paint.setStroke", json!({"ids": [id], "none": true})).unwrap(); + ok_with_bleed(&mut app, 4.0); + assert!(!short(&app), "{}", app.ui.status); + ok_with_bleed(&mut app, 9.0); + assert_eq!(app.ui.status, "1 object reaches the trim edge but stops short of the bleed"); + ok_with_bleed(&mut app, 6.0); + assert!(!short(&app), "{}", app.ui.status); + // Only the sides whose bleed grows count: the background stops short at the top, left and + // right, so a larger bottom bleed alone shows no note, and a larger top bleed does. + ok_with_sides(&mut app, [6.0, 12.0, 6.0, 6.0]); + assert!(!short(&app), "{}", app.ui.status); + ok_with_sides(&mut app, [12.0, 12.0, 6.0, 6.0]); + assert!(short(&app), "{}", app.ui.status); + // Art inside the trim falls short of no bleed. + 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(); + ok_with_bleed(&mut app, 9.0); + assert!(!short(&app), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().doc.setup.bleed, [9.0; 4]); + // A bleed that isn't a number, as a file can hold, counts as none before OK, as in the PDF. + 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": 0, "y": 0, "width": 200, "height": 50})).unwrap(); + std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc).setup.bleed = [f64::NAN; 4]; + ok_with_bleed(&mut app, 9.0); + assert_eq!(app.ui.status, "1 object reaches the trim edge but stops short of the bleed"); + } + /// Highlight Substituted Fonts is in Preferences › Type, so the General tab shows only the /// substituted glyphs highlight, and OK still applies. #[test] @@ -783,6 +908,36 @@ mod tests { } } + /// When Grid Colors holds a preset name (in any letter case) or a list that is not two colors, + /// the boxes and hex fields show the preset's pair or the document's, a box opens the Color + /// Picker on its color, and the picker's OK sets only that entry of a two-color list. + #[test] + fn a_grid_color_box_opens_on_a_preset_name_or_a_short_list() { + for (field, index, opens, kept, name) in [ + (json!("Blue"), 1, "#c4dcff", "#ffffff", "Blue"), + (json!("purple"), 0, "#ffffff", "#e2c9ff", "Purple"), + (json!(["#ff0000"]), 1, "#cccccc", "#ffffff", "Light"), + ] { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), field.clone()); + dialog_frame(&mut app, &ctx, vec![]); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for shown in [name, opens.trim_start_matches('#'), kept.trim_start_matches('#')] { + assert!(texts.iter().any(|t| t.eq_ignore_ascii_case(shown)), "{field}: no {shown} in {texts:?}"); + } + click_grid_box(&mut app, &ctx, index); + assert_picker_over_setup(&app, opens, &field.to_string()); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#00ff00")); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + let mut pair = [hex(kept); 2]; + pair[index] = hex("#00ff00"); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.to_vec()), "{field}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, pair, "{field}"); + } + } + /// With a preset name in Document Setup's `gridColors` field, the grid color boxes show the /// preset's colors, and the Color Picker opens on the clicked one; its OK sets that color and /// keeps the preset's other one. @@ -912,4 +1067,119 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); assert_eq!(undo_steps(&app), 0); } + + /// The grid preview Document Setup draws, in a fresh context: its rect, the texture + /// coordinates of its bottom-right corner (two cells per unit) and the tile's four pixels. + fn grid_preview(app: &mut VectorcraftApp) -> (Rect, egui::Vec2, Vec) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let (mut mesh, mut pixels) = (None, None); + for _ in 0..3 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + let tiles: Vec = + ctx.tex_manager().read().allocated().filter(|(_, m)| m.name == crate::canvas::TRANSPARENCY_GRID).map(|(id, _)| *id).collect(); + for (id, deltas) in &out.textures_delta.set { + if tiles.contains(id) + && let Some(d) = deltas.last() + { + let egui::ImageData::Color(img) = &d.image; + pixels = Some(img.pixels.clone()); + } + } + out.textures_delta.clear(); + mesh = out.shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Mesh(m) if tiles.contains(&m.texture_id) => Some(m.clone()), + _ => None, + }); + } + let mesh = mesh.unwrap_or_else(|| panic!("no grid preview")); + let uv = mesh.vertices.iter().fold(vec2(0.0, 0.0), |a, v| a.max(v.uv.to_vec2())); + (mesh.calc_bounds(), uv, pixels.unwrap_or_else(|| panic!("no tile"))) + } + + /// The tile's pixels for the grid colors `a` and `b`: `a` in the top-left and bottom-right cells. + fn tile(a: &str, b: &str) -> Vec { + let c = |h| crate::panels::c32(&hex(h)); + vec![c(a), c(b), c(b), c(a)] + } + + /// The Transparency tab shows a checkered preview of the grid its Grid Size and Grid Colors + /// hold before OK: the canvas's cells, the first color in the top-left cell. Simulate Colored + /// Paper leaves it checkered, and neither it nor Cancel changes the document. + #[test] + fn the_transparency_tab_previews_the_pending_grid_size_and_colors() { + let (mut app, _) = transparency_tab(); + let (rect, uv, pixels) = grid_preview(&mut app); + assert_eq!(rect.size(), super::GRID_PREVIEW); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile(LIGHT[0], LIGHT[1])), "Medium, Light"); + for (size, cell) in [("small", 4.0), ("large", 16.0)] { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("gridSize".into(), json!(size)); + d.fields.insert("gridColors".into(), json!(["#ff0000", "#0000ff"])); + let (rect, uv, pixels) = grid_preview(&mut app); + assert_eq!((uv, pixels), (rect.size() / (2.0 * cell), tile("#ff0000", "#0000ff")), "{size}"); + } + app.ui.dialog.as_mut().unwrap().fields.insert("simulatePaper".into(), json!(true)); + let (rect, uv, pixels) = grid_preview(&mut app); + assert_eq!((uv, pixels), (rect.size() / 32.0, tile("#ff0000", "#0000ff")), "Simulate Colored Paper"); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_size, st.doc.setup.grid_colors), (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex))); + assert_eq!(undo_steps(&app), 0); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + assert_eq!( + (st.doc.setup.grid_size, st.doc.setup.grid_colors, st.doc.setup.simulate_paper), + (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex), false) + ); + assert_eq!(undo_steps(&app), 0); + } + + /// The grid preview sits beside Grid Size, Grid Colors and the color boxes, inside the dialog, + /// and covers none of the tab's text or color boxes. + #[test] + fn the_grid_preview_sits_beside_the_grid_rows() { + let (mut app, ctx) = transparency_tab(); + let texts = dialog_frame(&mut app, &ctx, vec![]); + let (rect, _, _) = grid_preview(&mut app); + let label = texts.iter().find(|(t, _)| t == "Grid Size:").unwrap_or_else(|| panic!("no Grid Size: {texts:?}")).1; + assert!(rect.top() <= label.bottom() && rect.left() > label.right(), "{rect:?} beside {label:?}"); + for (text, r) in &texts { + assert!(!r.intersects(rect), "{text:?} at {r:?} under the preview {rect:?}"); + } + for i in 0..2 { + let r = ctx.read_response(super::grid_color_box_id(i)).unwrap().rect; + assert!(!r.intersects(rect), "box {i} at {r:?} under the preview {rect:?}"); + } + // The dialog's content is 540 points wide from its heading's left edge. + let left = texts.iter().find(|(t, _)| t == "Document Setup").unwrap_or_else(|| panic!("no heading: {texts:?}")).1.left(); + assert!(rect.right() <= left + 540.0 + 0.5, "{rect:?} inside the dialog from {left}"); + } + + /// A grid size or color pair the dialog holds that is not a valid value shows as the + /// document's setting. + #[test] + fn the_grid_preview_shows_the_document_setting_for_a_bad_field() { + let setup = vectorcraft_doc::DocSetup { + grid_size: vectorcraft_doc::GridSize::Large, + grid_colors: [hex("#111111"), hex("#222222")], + ..Default::default() + }; + let fields = |v: serde_json::Value| v.as_object().unwrap().clone(); + for bad in [ + json!({}), + json!({"gridSize": "huge", "gridColors": ["#ff0000"]}), + json!({"gridSize": 3, "gridColors": ["#ff0000", "zz"]}), + json!({"gridColors": "Plaid"}), + json!({"gridColors": ["#ff0000", "#00ff00", "#0000ff"]}), + ] { + assert_eq!(super::preview_grid(&fields(bad.clone()), &setup), (setup.grid_size, setup.grid_colors), "{bad}"); + } + let good = fields(json!({"gridSize": "small", "gridColors": ["#ff0000", "#0000ff"]})); + assert_eq!(super::preview_grid(&good, &setup), (vectorcraft_doc::GridSize::Small, [hex("#ff0000"), hex("#0000ff")])); + let preset = fields(json!({"gridColors": "blue"})); + assert_eq!(super::preview_grid(&preset, &setup), (vectorcraft_doc::GridSize::Large, [hex("#ffffff"), hex("#c4dcff")])); + } } diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs new file mode 100644 index 0000000000..8e229980e6 --- /dev/null +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -0,0 +1,387 @@ +//! Edit › Find and Replace…: the Find and Replace With fields, Match Case, Find Whole Word, Search +//! Backwards, Check Hidden Layers and Check Locked Layers, and the Find, Replace, Replace & Find, +//! Replace All and Done buttons, as "Find and replace text" in the public +//! [reference](https://helpx.adobe.com/pdf/illustrator_reference.pdf) describes them. The dialog +//! stays open: Find goes to the next match (`edit.findNext`), Replace changes that match +//! (`edit.replaceMatch`), Replace & Find changes it and goes to the next, and Replace All changes +//! every match (`edit.findReplace`). Each Replace is one undo step, and so is Replace All. +//! +//! These rules are VectorCraft's own. A match is shown in the dialog in its line of text with its +//! place among the matches, and its type object is selected, unless it is on a hidden or locked +//! layer. Enter runs Find. Replace and Replace & Find wait for a match that Find reached with the +//! Find text and the options as they are now. Edit › Find Next goes on from the last search while +//! the dialog is closed, and opens the dialog when there has been none. +//! +//! Fields: `find`, `replace`, `matchCase`, `wholeWord`, `backwards`, `hiddenLayers`, +//! `lockedLayers` and `action` (what `ui.dialog.confirm` does: `find`, `replace`, `replaceFind`, +//! `replaceAll` or `done`; a button sets it and confirms). The dialog keeps the place the search +//! reached in `__at`, the `uid` of its document in `__doc` and the Find text and switches it was +//! reached with in `__atQuery`, the match found in `__found` and the line under the fields in +//! `__note`. A place in a document other than the active one, or reached with other Find text or +//! switches, is not used: the search starts again. + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use super::{DialogAction, DialogSpec, form}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Find and Replace. +pub const KIND: &str = "findReplace"; + +/// The command of its menu item, which Replace All runs. +pub const COMMAND: &str = "edit.findReplace"; + +/// The command Find runs, and Edit › Find Next. +pub const NEXT: &str = "edit.findNext"; + +/// The command Replace runs. +const REPLACE: &str = "edit.replaceMatch"; + +/// The switches that decide what a match is and which type is searched. +const SWITCHES: [&str; 4] = ["matchCase", "wholeWord", "hiddenLayers", "lockedLayers"]; + +/// The place the search reached: `{id, start, end}`, a match or the text that replaced one. +const AT: &str = "__at"; +/// The match Find reached, which Replace changes: `{index, count, query}`, with `query` the Find +/// text and the switches it was found with. +const FOUND: &str = "__found"; +/// The line under the fields, in English: no matches, or how many Replace All replaced. +const NOTE: &str = "__note"; + +/// The characters of a match's line shown on either side of it. +const CONTEXT: usize = 24; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Find and Replace").into(), + body_with_actions: Some(body), + confirm, + ok: None, + min_width: 480.0, + ..DialogSpec::FORM +}; + +/// The document a place in [`AT`] or the last search's `from` belongs to: its `uid`. +const DOC: &str = "__doc"; +/// The Find text and switches the place in [`AT`] was reached with ([`query`]). +const AT_QUERY: &str = "__atQuery"; + +/// The params of the Edit menu's Find and Replace… item: a `find` of null, which gives the dialog +/// no field, so that it opens on the last search. +pub fn menu_params() -> Value { + json!({"find": null}) +} + +/// The `uid` of the active document. +fn active_uid(app: &VectorcraftApp) -> Option { + app.session.active().map(|d| d.uid) +} + +/// Open Find and Replace on the last search when there has been one, with the fields that +/// `params` gives in its place. A null value, such as the menu item's `find` ([`menu_params`]), +/// gives none. A field given a value of another type is an error, and the dialog does not open. +pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result { + let mut fields = Map::new(); + fields.insert("find".into(), json!("")); + fields.insert("replace".into(), json!("")); + for key in SWITCHES.into_iter().chain(["backwards"]) { + fields.insert(key.into(), json!(false)); + } + check_types(params, true)?; + let last = app.ui.last_find.as_ref().and_then(Value::as_object).cloned().unwrap_or_default(); + for (k, v) in last.iter().chain(params) { + // Only the dialog's own fields, each of its own type. + if fields.get(k).is_some_and(|f| f.is_string() == v.is_string() && f.is_boolean() == v.is_boolean()) { + fields.insert(k.clone(), v.clone()); + } + } + // The place the last search reached, while its document is the active one. + let uid = active_uid(app); + if let Some(at) = last.get("from").filter(|v| v.is_object() && uid.is_some() && last.get("doc").and_then(Value::as_u64) == uid) { + fields.insert(AT.into(), at.clone()); + fields.insert(DOC.into(), json!(uid)); + fields.insert(AT_QUERY.into(), query_in(&last)); + } + fields.insert("action".into(), json!("find")); + fields.insert("__command".into(), json!(COMMAND)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(Value::Null) +} + +/// The first of the dialog's fields in `fields` that holds a value of another type than its own, +/// as an error: `find` and `replace` are strings, and `backwards` and the [`SWITCHES`] are true or +/// false. A null value is no error when `null_gives_none` is true. +fn check_types(fields: &Map, null_gives_none: bool) -> Result<(), String> { + for (k, v) in fields.iter().filter(|(_, v)| !(null_gives_none && v.is_null())) { + if matches!(k.as_str(), "find" | "replace") && !v.is_string() { + return Err(format!("`{k}` must be a string")); + } + if (k == "backwards" || SWITCHES.contains(&k.as_str())) && !v.is_boolean() { + return Err(format!("`{k}` must be true or false")); + } + } + Ok(()) +} + +/// Edit › Find Next with no text to find: the next match of the last search, from the place it +/// reached, with the options the dialog had. With no search yet, it opens the dialog. +pub fn find_next(app: &mut VectorcraftApp) -> Result { + let Some(mut last) = app.ui.last_find.clone().filter(|l| l.get("find").and_then(Value::as_str).is_some_and(|f| !f.is_empty())) else { + return open(app, &Map::new()); + }; + let uid = active_uid(app); + if let Some(o) = last.as_object_mut() { + o.remove("replace"); + // A place in another document is no place in this one. + if uid.is_none() || o.remove("doc").and_then(|d| d.as_u64()) != uid { + o.remove("from"); + } + } + let r = app.run(NEXT, last)?; + if r["id"].is_null() { + app.status("No matches found"); + return Ok(r); + } + if let Some(l) = app.ui.last_find.as_mut() { + l["from"] = json!({ "id": r["id"], "start": r["start"], "end": r["end"] }); + l["doc"] = json!(uid); + } + Ok(r) +} + +/// The Find text and the switches of [`SWITCHES`]: what a match is, as params. +fn query(d: &Dialog) -> Value { + query_in(&d.fields) +} + +/// [`query`] of the dialog fields, or of the last search, in `fields`. +fn query_in(fields: &Map) -> Value { + let mut q = json!({ "find": fields.get("find").and_then(Value::as_str).unwrap_or_default() }); + for key in SWITCHES { + q[key] = json!(fields.get(key).and_then(Value::as_bool).unwrap_or(false)); + } + q +} + +/// The place the search reached, `{id, start, end}`, while its document is the active one and +/// the Find text and the switches are those it was reached with. +fn place<'a>(app: &VectorcraftApp, d: &'a Dialog) -> Option<&'a Value> { + let uid = active_uid(app)?; + let same = d.fields.get(DOC).and_then(Value::as_u64) == Some(uid) && d.fields.get(AT_QUERY) == Some(&query(d)); + same.then(|| d.fields.get(AT)).flatten().filter(|at| at.is_object()) +} + +/// Keep `at`, a place in the active document, as the place the search reached. +fn set_place(app: &VectorcraftApp, d: &mut Dialog, at: Value) { + d.fields.insert(AT.into(), at); + d.fields.insert(DOC.into(), json!(active_uid(app))); + d.fields.insert(AT_QUERY.into(), query(d)); +} + +/// The match Replace changes, as `{id, start, end}`: the one Find reached in the active document, +/// while the Find text and the switches are as they were when it was found. +fn current_match<'a>(app: &VectorcraftApp, d: &'a Dialog) -> Option<&'a Value> { + let found = d.fields.get(FOUND)?; + (found.get("query") == Some(&query(d))).then(|| place(app, d)).flatten() +} + +/// Keep what the dialog searched for and the place it reached, for Edit › Find Next and for the +/// next time the dialog opens. +fn remember(app: &mut VectorcraftApp, d: &Dialog) { + let mut last = query(d); + last["replace"] = json!(d.str("replace")); + last["backwards"] = json!(d.bool("backwards")); + if let Some(at) = place(app, d) { + last["from"] = at.clone(); + last["doc"] = json!(active_uid(app)); + } + app.ui.last_find = Some(last); +} + +/// Find: the next match after the place the search reached, kept as that place and as the match +/// Replace changes. With no match, the note says so. +fn find(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let mut p = query(d); + p["backwards"] = json!(d.bool("backwards")); + // With no place, the search starts at the first match, not after the selected type object. + p["from"] = place(app, d).cloned().unwrap_or(Value::Null); + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(NEXT, p)?; + if r["id"].is_null() { + app.status("No matches found"); + d.fields.insert(NOTE.into(), json!(app.ui.status)); + return Ok(r); + } + set_place(app, d, json!({ "id": r["id"], "start": r["start"], "end": r["end"] })); + d.fields.insert(FOUND.into(), json!({ "index": r["index"], "count": r["count"], "query": query(d) })); + Ok(r) +} + +/// Replace: the match Find reached becomes the Replace With text, and the search goes on from +/// it. With no such match, it finds one. +fn replace(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let Some(at) = current_match(app, d).cloned() else { return find(app, d) }; + let mut p = query(d); + for key in ["hiddenLayers", "lockedLayers"] { + if let Some(o) = p.as_object_mut() { + o.remove(key); + } + } + p["replace"] = json!(d.str("replace")); + for key in ["id", "start", "end"] { + p[key] = at[key].clone(); + } + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(REPLACE, p)?; + set_place(app, d, json!({ "id": r["id"], "start": r["start"], "end": r["end"] })); + Ok(r) +} + +/// Replace All: every match becomes the Replace With text, and the note says how many. +fn replace_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let mut p = query(d); + p["replace"] = json!(d.str("replace")); + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(COMMAND, p)?; + // The matches that changed: those that already read as the Replace With text do not count. + match (r["count"].as_u64().unwrap_or(0), r["replaced"].as_u64().unwrap_or(0)) { + (0, _) => app.status("No matches found"), + (_, n) => app.status(format!("Matches replaced: {n}")), + } + d.fields.insert(NOTE.into(), json!(app.ui.status)); + Ok(r) +} + +/// A button or `ui.dialog.confirm`: run the `action` and keep the dialog open, or close it for +/// `done`. What a command refuses is the note, and the dialog stays open. A field set to a value +/// of another type than its own ([`check_types`]) runs no action: the error is the note, shown +/// under the match found, which Replace still changes once the field is set right. So does an +/// `action` that is not a string. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut d = d.clone(); + let action = d.fields.insert("action".into(), json!("find")); + let checked = match &action { + Some(a) if !a.is_string() => Err("`action` must be a string".to_string()), + _ => check_types(&d.fields, false), + }; + if let Err(e) = checked { + d.fields.insert(NOTE.into(), json!(e)); + app.ui.dialog = Some(d); + return Err(e); + } + let r = match action.as_ref().and_then(Value::as_str).unwrap_or_default() { + "done" => { + remember(app, &d); + app.ui.dialog = None; + return Ok(Value::Null); + } + "" | "find" => find(app, &mut d), + "replace" => replace(app, &mut d), + "replaceFind" => match current_match(app, &d) { + Some(_) => replace(app, &mut d).and_then(|_| find(app, &mut d)), + None => find(app, &mut d), + }, + "replaceAll" => replace_all(app, &mut d), + _ => Err("no such action".to_string()), + }; + if let Err(e) = &r { + d.fields.insert(NOTE.into(), json!(e)); + } + remember(app, &d); + app.ui.dialog = Some(d); + r +} + +/// The match Find reached as it reads in its text: (the text before it on its line, the match, +/// the text after it), each at most [`CONTEXT`] characters, and its place among the matches. +fn shown_match(app: &VectorcraftApp, d: &Dialog) -> Option<([String; 3], String)> { + let at = current_match(app, d)?; + let found = d.fields.get(FOUND)?; + let whole = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()); + let (id, start, end) = (at["id"].as_u64()?, whole(&at["start"])?, whole(&at["end"])?); + let NodeKind::Text(t) = &app.session.active()?.doc.node(NodeId(id))?.kind else { return None }; + let text = t.plain_text(); + let (before, hit, after) = (text.get(..start)?, text.get(start..end)?, text.get(end..)?); + let before = before.rsplit(['\n', '\r']).next().unwrap_or_default(); + let after = after.split(['\n', '\r']).next().unwrap_or_default(); + let skip = before.chars().count().saturating_sub(CONTEXT); + let lead = if skip > 0 { "…" } else { "" }; + let tail = if after.chars().count() > CONTEXT { "…" } else { "" }; + let before = format!("{lead}{}", before.chars().skip(skip).collect::()); + let after = format!("{}{tail}", after.chars().take(CONTEXT).collect::()); + Some(([before, hit.to_string(), after], format!("{} / {}", found["index"], found["count"]))) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let can_find = !d.str("find").is_empty(); + let found = current_match(app, d).is_some(); + let mut action = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + widgets::dim_label(ui, tl!("Find:")); + form::text(ui, d, "find", 320.0); + ui.add_space(6.0); + widgets::dim_label(ui, tl!("Replace With:")); + form::text(ui, d, "replace", 320.0); + ui.add_space(10.0); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + form::check(ui, d, "matchCase", "Match Case"); + form::check(ui, d, "wholeWord", "Find Whole Word"); + form::check(ui, d, "backwards", "Search Backwards"); + }); + ui.add_space(16.0); + ui.vertical(|ui| { + form::check(ui, d, "hiddenLayers", "Check Hidden Layers"); + form::check(ui, d, "lockedLayers", "Check Locked Layers"); + }); + }); + }); + ui.add_space(16.0); + ui.vertical(|ui| { + let mut button = |ui: &mut egui::Ui, label: &str, enabled: bool, name: &'static str| { + if ui.add_enabled_ui(enabled, |ui| widgets::flat_button(ui, label, 130.0).clicked()).inner { + action = Some(name); + } + ui.add_space(6.0); + }; + button(ui, if found { tl!("Find Next") } else { tl!("Find") }, can_find, "find"); + button(ui, tl!("Replace"), can_find && found, "replace"); + button(ui, tl!("Replace & Find"), can_find && found, "replaceFind"); + button(ui, tl!("Replace All"), can_find, "replaceAll"); + button(ui, tl!("Done"), true, "done"); + }); + }); + ui.add_space(8.0); + if let Some(([before, hit, after], place)) = shown_match(app, d) { + let t = crate::theme::Tokens::get(ui.ctx()); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + widgets::dim_name(ui, &format!("{place} {before}")); + ui.colored_label(t.text_strong, egui::RichText::new(hit).strong().underline()); + widgets::dim_name(ui, &after); + }); + } + // Find and Replace remove the note, so it shows under a match only when an action was refused. + if let Some(note) = d.fields.get(NOTE).and_then(Value::as_str) { + widgets::dim_name(ui, &crate::i18n::message(crate::i18n::current(), note)); + } + // Enter finds, as the Find button does. + if action.is_none() && can_find && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + action = Some("find"); + } + match action { + Some(name) => { + d.fields.insert("action".into(), json!(name)); + DialogAction::Confirm + } + None => DialogAction::None, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs new file mode 100644 index 0000000000..1f2bb756ab --- /dev/null +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -0,0 +1,458 @@ +use egui::{Event, PointerButton, Pos2, Rect, vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::VectorcraftApp; + +/// An app on a document holding point type `texts`, bottom first, with nothing selected → the +/// app and the type objects' ids. +fn app_with(texts: &[&str]) -> (VectorcraftApp, Vec) { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ids = texts.iter().map(|t| s.execute("text.create", &json!({"x": 50, "y": 50, "text": t})).unwrap()["id"].as_u64().unwrap()).collect(); + s.execute("select.none", &json!({})).unwrap(); + (VectorcraftApp::new(s, crate::Services::default()), ids) +} + +/// Choose Edit › Find and Replace…, as a click on the menu item does. +fn choose(app: &mut VectorcraftApp) { + let (id, p) = crate::shortcut_editor::menu_target(super::COMMAND).expect("the menu item gives params"); + crate::menus::invoke(app, &id, p); +} + +/// Choose Edit › Find Next, as a click on the menu item does. +fn choose_find_next(app: &mut VectorcraftApp) { + let e = crate::menus::menu_entries(app).into_iter().find(|e| e.label == "Find Next").expect("in the Edit menu"); + assert_eq!((e.command.as_deref(), e.enabled), (Some(super::NEXT), true)); + crate::menus::invoke(app, super::NEXT, json!({"find": ""})); +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); +} + +fn field(app: &VectorcraftApp, k: &str) -> Value { + app.ui.dialog.as_ref().expect("the dialog is open").fields.get(k).cloned().unwrap_or(Value::Null) +} + +/// The match Replace would change, as (object, start, end). +fn matched(app: &VectorcraftApp) -> Option<(u64, u64, u64)> { + let at = super::current_match(app, app.ui.dialog.as_ref()?)?; + Some((at["id"].as_u64()?, at["start"].as_u64()?, at["end"].as_u64()?)) +} + +fn plain(app: &VectorcraftApp, id: u64) -> String { + match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not type"), + } +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +fn selected(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect() +} + +/// One frame of the dialog on an 800 × 600 window → the text painted, with its rect. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect)> { + // A window takes a sizing frame and fades in: each frame is a quarter second on. + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx +} + +fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> Vec<(String, Rect)> { + frame(app, ctx, vec![]); + let texts = frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at)]); + frame(app, ctx, vec![press(true)]); + frame(app, ctx, vec![press(false)]); + frame(app, ctx, vec![]) +} + +/// Edit › Find and Replace… opens the dialog of its own, with the fields and options of the +/// public reference's "Find and replace text", instead of the generic parameter dialog. +#[test] +fn the_edit_menu_opens_the_find_and_replace_dialog() { + let (mut app, _) = app_with(&["cat"]); + let e = crate::menus::menu_entries(&app).into_iter().find(|e| e.label == "Find and Replace…").expect("in the Edit menu"); + assert_eq!((e.path.as_slice(), e.command.as_deref(), e.enabled), (&["Edit".to_string()][..], Some(super::COMMAND), true)); + choose(&mut app); + let d = app.ui.dialog.as_ref().expect("Find and Replace opens"); + assert_eq!((d.kind.as_str(), d.fields["__command"].clone()), (super::KIND, json!(super::COMMAND))); + for (key, want) in [("find", json!("")), ("replace", json!("")), ("action", json!("find"))] { + assert_eq!(d.fields[key], want, "{key}"); + } + for key in ["matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers"] { + assert_eq!(d.fields[key], json!(false), "{key}"); + } + let ctx = context(); + frame(&mut app, &ctx, vec![]); + let texts: Vec = frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for label in [ + "Find and Replace", + "Find:", + "Replace With:", + "Match Case", + "Find Whole Word", + "Search Backwards", + "Check Hidden Layers", + "Check Locked Layers", + "Find", + "Replace", + "Replace & Find", + "Replace All", + "Done", + ] { + assert!(texts.iter().any(|t| t == label), "no `{label}` in {texts:?}"); + } +} + +/// A field given a value of another type than its own is an error and the dialog does not open; a +/// null value gives no field. A field set to such a value once the dialog is open runs no action: +/// the error is the note, shown under the match found, and the text, the match and the last search +/// stay as they were. +#[test] +fn the_dialog_rejects_a_field_of_the_wrong_type() { + let (mut app, ids) = app_with(&["cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + let last = app.ui.last_find.clone(); + for (k, v, want) in [ + ("replace", json!(5), "`replace` must be a string"), + ("replace", Value::Null, "`replace` must be a string"), + ("matchCase", json!("yes"), "`matchCase` must be true or false"), + ] { + set(&mut app, k, v.clone()); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap_err(), want, "{k}: {v}"); + assert_eq!((plain(&app, ids[0]), field(&app, "__note"), app.ui.last_find.clone()), ("cat".to_string(), json!(want), last.clone())); + assert_eq!(matched(&app), Some((ids[0], 0, 3)), "Replace still changes the match found"); + let ctx = context(); + frame(&mut app, &ctx, vec![]); + let texts: Vec = frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == want) && texts.iter().any(|t| t == "cat"), "the note shows under the match: {texts:?}"); + set(&mut app, k, if k == "replace" { json!("dog") } else { json!(false) }); + } + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + let open = |app: &mut VectorcraftApp, params: Value| app.run("ui.paramDialog", json!({"command": super::COMMAND, "params": params})); + for (params, want) in [ + (json!({"find": 17}), "`find` must be a string"), + (json!({"replace": true}), "`replace` must be a string"), + (json!({"matchCase": "yes"}), "`matchCase` must be true or false"), + (json!({"backwards": 1}), "`backwards` must be true or false"), + ] { + assert_eq!(open(&mut app, params.clone()).unwrap_err(), want, "{params}"); + assert!(app.ui.dialog.is_none(), "{params}"); + } + open(&mut app, json!({"find": null, "replace": "dog", "wholeWord": true})).unwrap(); + assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "wholeWord")), (json!("cat"), json!("dog"), json!(true))); +} + +/// An `action` that is not a string runs no action, Find included: the error is the note, and the +/// match found, the selection and the last search stay as they were. +#[test] +fn an_action_of_the_wrong_type_runs_no_action() { + let (mut app, _) = app_with(&["cat", "cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + let (at, sel, last) = (matched(&app), selected(&app), app.ui.last_find.clone()); + assert!(at.is_some()); + for v in [json!(5), Value::Null, json!(["find"])] { + set(&mut app, "action", v.clone()); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap_err(), "`action` must be a string", "{v}"); + assert_eq!((matched(&app), selected(&app), app.ui.last_find.clone()), (at, sel.clone(), last.clone()), "{v}"); + assert_eq!(field(&app, "__note"), json!("`action` must be a string"), "{v}"); + } + set(&mut app, "action", json!("find")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_ne!(matched(&app), at, "a string action still runs"); +} + +/// Find with other Find text starts again at the first match, the matches in the type object the +/// last Find selected included. +#[test] +fn find_with_other_text_starts_at_the_first_match() { + let (mut app, ids) = app_with(&["dog", "cat dog"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((matched(&app), selected(&app)), (Some((top, 0, 3)), vec![top])); + set(&mut app, "find", json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((matched(&app), selected(&app)), (Some((top, 4, 7)), vec![top])); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); +} + +/// The dialog stays open from match to match: Find goes to the next match and selects its +/// object, Replace changes that match, Replace & Find changes it and goes on, Replace All changes +/// the rest, and Done closes. Each Replace is one undo step, and so is Replace All; finding and a +/// Replace All with nothing to replace record none. +#[test] +fn the_buttons_step_through_the_matches() { + let (mut app, ids) = app_with(&["cat cat", "a cat"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + let ctx = context(); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + let steps = undo_steps(&app); + // Find: the first match, in the top object, shown with its place and its line of text. + let texts = click(&mut app, &ctx, "Find"); + assert_eq!((matched(&app), selected(&app), undo_steps(&app)), (Some((top, 2, 5)), vec![top], steps)); + assert!(texts.iter().any(|(t, _)| t.starts_with("1 / 3")) && texts.iter().any(|(t, _)| t == "cat"), "{texts:?}"); + assert!(texts.iter().any(|(t, _)| t == "Find Next"), "Find reads Find Next once a match is found: {texts:?}"); + // Replace: that match only, and the search stays where it was. + click(&mut app, &ctx, "Replace"); + assert_eq!((plain(&app, top), plain(&app, bottom), undo_steps(&app)), ("a dog".to_string(), "cat cat".to_string(), steps + 1)); + assert_eq!((matched(&app), field(&app, "__at")), (None, json!({"id": top, "start": 2, "end": 5}))); + // Find goes on from there, to the bottom object. + click(&mut app, &ctx, "Find"); + assert_eq!((matched(&app), selected(&app), field(&app, "__found")["count"].clone()), (Some((bottom, 0, 3)), vec![bottom], json!(2))); + // Replace & Find: one undo step, and the next match is the one left. + click(&mut app, &ctx, "Replace & Find"); + assert_eq!((plain(&app, bottom), undo_steps(&app), matched(&app)), ("dog cat".to_string(), steps + 2, Some((bottom, 4, 7)))); + // Replace All: the rest as one undo step, with the count under the fields. + let texts = click(&mut app, &ctx, "Replace All"); + assert_eq!((plain(&app, bottom), undo_steps(&app), matched(&app)), ("dog dog".to_string(), steps + 3, None)); + assert!(texts.iter().any(|(t, _)| t == "Matches replaced: 1"), "{texts:?}"); + // Nothing left: no undo step, and the dialog says so, for Replace All and for Find. + for button in ["Replace All", "Find"] { + let texts = click(&mut app, &ctx, button); + assert_eq!((undo_steps(&app), matched(&app)), (steps + 3, None), "{button}"); + assert!(texts.iter().any(|(t, _)| t == "No matches found"), "{button}: {texts:?}"); + } + assert!(app.ui.dialog.is_some(), "the dialog stays open until Done"); + click(&mut app, &ctx, "Done"); + assert!(app.ui.dialog.is_none(), "Done closes it"); + assert_eq!(undo_steps(&app), steps + 3); +} + +/// Replace and Replace & Find wait for a match found with the Find text and the options as they +/// are: before the first Find, and after the Find text changes, a click on them changes nothing. +/// With no Find text, no button but Done acts. Enter runs Find. +#[test] +fn replace_waits_for_a_match_of_the_text_as_it_is() { + let (mut app, ids) = app_with(&["cat cart"]); + choose(&mut app); + let ctx = context(); + let steps = undo_steps(&app); + set(&mut app, "replace", json!("x")); + for button in ["Find", "Replace", "Replace & Find", "Replace All"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), matched(&app)), ("cat cart".to_string(), steps, None), "{button} with no Find text"); + } + set(&mut app, "find", json!("cat")); + for button in ["Replace", "Replace & Find"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), matched(&app)), ("cat cart".to_string(), steps, None), "{button} before Find"); + } + // Enter finds. + frame(&mut app, &ctx, vec![]); + let enter = |pressed| Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![enter(true)]); + frame(&mut app, &ctx, vec![enter(false)]); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + // The Find text changes: the match found is no longer the one to replace. + set(&mut app, "find", json!("ca")); + assert_eq!(matched(&app), None); + for button in ["Replace", "Replace & Find"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("cat cart".to_string(), steps), "{button} after the Find text changed"); + } + // An option changes: the same. + set(&mut app, "find", json!("cat")); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + set(&mut app, "matchCase", json!(true)); + assert_eq!(matched(&app), None); + // Search Backwards is a direction, not what a match is. + set(&mut app, "matchCase", json!(false)); + set(&mut app, "backwards", json!(true)); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + click(&mut app, &ctx, "Replace"); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("x cart".to_string(), steps + 1)); +} + +/// `ui.dialog.confirm` runs the dialog's `action`, keeps it open and puts `action` back to find; +/// done closes it. An action it does not know is refused, and so is an empty Find text. +#[test] +fn confirm_runs_the_action() { + let (mut app, ids) = app_with(&["cat cat cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + let steps = undo_steps(&app); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((r["start"].clone(), r["index"].clone(), r["count"].clone(), matched(&app)), (json!(0), json!(1), json!(3), Some((ids[0], 0, 3)))); + set(&mut app, "action", json!("replaceFind")); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), r["start"].clone(), field(&app, "action")), ("dog cat cat".to_string(), json!(4), json!("find"))); + set(&mut app, "action", json!("replace")); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), r["replaced"].clone(), matched(&app)), ("dog dog cat".to_string(), json!(true), None)); + // Replace with no match found: it finds one. + set(&mut app, "action", json!("replace")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), matched(&app), undo_steps(&app)), ("dog dog cat".to_string(), Some((ids[0], 8, 11)), steps + 2)); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap(), json!({"count": 1, "replaced": 1})); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("dog dog dog".to_string(), steps + 3)); + // Matches that already read as the Replace With text are found and not counted as replaced. + set(&mut app, "find", json!("DOG")); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap(), json!({"count": 3, "replaced": 0})); + assert_eq!((undo_steps(&app), field(&app, "__note")), (steps + 3, json!("Matches replaced: 0"))); + set(&mut app, "find", json!("dog")); + for (action, find) in [("erase", "dog"), ("find", ""), ("replaceAll", "")] { + set(&mut app, "action", json!(action)); + set(&mut app, "find", json!(find)); + assert!(crate::dialogs::confirm(&mut app).is_err(), "{action} {find:?}"); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), field(&app, "action")), ("dog dog dog".to_string(), steps + 3, json!("find"))); + assert!(field(&app, "__note").is_string(), "{action} {find:?}: the dialog shows why"); + } + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); +} + +/// Edit › Find Next goes on from the dialog's last search while the dialog is closed, with its +/// options, and says when nothing matches. With no search yet, it opens the dialog, and the +/// dialog opens again on the last search. +#[test] +fn find_next_goes_on_from_the_last_search() { + let (mut app, ids) = app_with(&["Cat", "cat", "cat"]); + choose_find_next(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND), "no search yet: the dialog opens"); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + set(&mut app, "matchCase", json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((ids[2], 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + let steps = undo_steps(&app); + // On from the match the dialog found; Match Case still leaves out "Cat". + for want in [ids[1], ids[2], ids[1]] { + choose_find_next(&mut app); + assert_eq!((selected(&app), app.ui.dialog.is_none(), undo_steps(&app)), (vec![want], true, steps)); + } + // The dialog opens on the last search and the place it reached. + choose(&mut app); + assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "matchCase")), (json!("cat"), json!("dog"), json!(true))); + assert_eq!(field(&app, "__at"), json!({"id": ids[1], "start": 0, "end": 3})); + set(&mut app, "find", json!("zebra")); + assert!(crate::dialogs::confirm(&mut app).unwrap()["id"].is_null()); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + app.ui.status.clear(); + choose_find_next(&mut app); + assert_eq!((app.ui.status.as_str(), selected(&app)), ("No matches found", vec![ids[1]])); +} + +/// The place a search reached goes with the Find text and the switches it was reached with: a +/// search for other text starts again, in the dialog and when `ui.paramDialog` gives other text, +/// and the same search goes on from that place. +#[test] +fn a_changed_search_starts_again() { + let (mut app, ids) = app_with(&["cat dog cat", "dog"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); + set(&mut app, "find", json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((top, 0, 3)), "not the dog after the cat found"); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": {"find": "dog"}})); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((top, 0, 3))); + app.ui.dialog = None; + choose(&mut app); + assert_eq!(field(&app, "find"), json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 4, 7)), "the same search goes on"); +} + +/// The place a search reached belongs to its document: in another document, Edit › Find Next and +/// the dialog start at that document's first match, even where an object there has the same id. +/// The params of a `ui.paramDialog` call take the place of the last search's, a switch that is off +/// included, while the menu item's own params leave the last search as it was. +#[test] +fn a_search_place_stays_in_its_document_and_given_params_win() { + let (mut app, ids) = app_with(&["cat cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + set(&mut app, "matchCase", json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + // A second document, whose type object has the id of the first one's. + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let other = app.run("text.create", json!({"x": 50, "y": 50, "text": "cat cat"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + assert_eq!(other, ids[0]); + choose_find_next(&mut app); + assert_eq!( + (selected(&app), app.ui.last_find.as_ref().map(|l| l["from"].clone())), + (vec![other], Some(json!({"id": other, "start": 0, "end": 3}))) + ); + // The dialog opens on the last search; Find goes on in this document. + choose(&mut app); + assert_eq!(field(&app, "matchCase"), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((other, 4, 7))); + // Back in the first document, the dialog's place is not used: Replace finds first and changes + // nothing. + assert!(app.session.set_active(0)); + assert_eq!(matched(&app), None); + set(&mut app, "replace", json!("dog")); + set(&mut app, "action", json!("replace")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), matched(&app)), ("cat cat".to_string(), Some((ids[0], 0, 3)))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + // Given params win over the last search; the menu item's own do not. + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": {"matchCase": false, "replace": "dog"}})); + assert_eq!((field(&app, "find"), field(&app, "matchCase"), field(&app, "replace")), (json!("cat"), json!(false), json!("dog"))); + app.ui.dialog = None; + let empty = json!({"find": "", "replace": "", "matchCase": false, "wholeWord": false}); + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": empty})); + assert_eq!((field(&app, "find"), field(&app, "matchCase")), (json!(""), json!(false))); + app.ui.dialog = None; + choose(&mut app); + assert_eq!((field(&app, "find"), field(&app, "matchCase")), (json!("cat"), json!(true))); +} diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index 5b6834d46e..8c5cbcf5fc 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -5,18 +5,22 @@ //! grid shows). While Alt (Option on macOS) is held, Cancel reads Reset, which puts every option //! back to the tool's default and leaves the dialog open (`ui.dialogReset`). A click-opened //! dialog previews its settings live; Reset refreshes that preview and Cancel rolls it back. +//! Opened from the toolbar with flares selected, it shows the first one's settings, and OK draws +//! the selected flares again with the settings changed in the dialog (`shape.editFlare`); the tool +//! keeps its options. //! //! Fields: the options (`vectorcraft_tools::extra::FLARE_OPTIONS`): `diameter` and `pathLength` //! (points), `opacity`, `brightness`, `growth`, `fuzziness`, `longest`, `rayFuzziness` and -//! `largest` (%), `rays` and `rings` (counts), `direction` (degrees); `raysOn` and `ringsOn`; and -//! `x`, `y` where a click opened it, with `preview` on initially for that click. +//! `largest` (%), `rays` and `rings` (counts), `direction` (degrees); `raysOn` and `ringsOn`; +//! `x`, `y` where a click opened it, with `preview` on initially for that click; and `flares` +//! (ids) with `shown` (the settings the dialog opened with) for the selected flares. use serde_json::{Map, Value, json}; use vectorcraft_geom::Point; use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params}; use super::document_setup::check; -use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; +use super::{DialogResult, DialogSpec, form, run_and_close, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -38,7 +42,8 @@ const LABEL_W: f32 = 78.0; const FIELD_W: f32 = 90.0; /// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a -/// flare there on OK. +/// flare there on OK. Opened without a click while flares are selected, they show the first one's +/// settings, to change the selected flares on OK. pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { let mut fields = match app.session.tool_options_of("flare") { Value::Object(o) => o, @@ -48,11 +53,79 @@ pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { fields.insert("preview".into(), json!(true)); fields.insert("x".into(), json!(p.x)); fields.insert("y".into(), json!(p.y)); + } else if let Some((ids, settings)) = selected_flares(app) { + // A flare without rays or rings shows that checkbox off, with the tool's count. + for (key, on) in [("rays", "raysOn"), ("rings", "ringsOn")] { + let n = settings.get(key).and_then(Value::as_f64).unwrap_or(0.0); + fields.insert(on.into(), json!(n > 0.0)); + if n > 0.0 { + fields.insert(key.into(), json!(n)); + } + } + for (key, ..) in FLARE_OPTIONS.iter().filter(|(k, ..)| !matches!(*k, "rays" | "rings")) { + if let Some(v) = settings.get(*key) { + fields.insert(key.to_string(), v.clone()); + } + } + fields.insert("shown".into(), Value::Object(shown(&fields))); + fields.insert("flares".into(), json!(ids)); } app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); json!({ "dialog": KIND }) } +/// The selected flares that can be edited (ids) and the first one's settings as the dialog shows +/// them: its rings' path length and direction from its center to its end point, where the flare is +/// drawn now. +fn selected_flares(app: &VectorcraftApp) -> Option<(Vec, Map)> { + let st = app.session.doc().ok()?; + let flares: Vec<_> = st + .selection + .objects + .iter() + .filter(|id| st.doc.is_editable(**id)) + .filter_map(|id| vectorcraft_engine::flare_settings(&st.doc, *id).map(|spec| (id.0, spec))) + .collect(); + let (_, first) = flares.first()?; + let Value::Object(mut settings) = first.params.clone() else { return None }; + let d = first.end()? - first.center()?; + settings.insert("pathLength".into(), json!(d.hypot())); + // Counter-clockwise from 3 o'clock, 0° to 360°, as `shape.flare` takes it. + settings.insert("direction".into(), json!((-d.y).atan2(d.x).to_degrees().rem_euclid(360.0))); + Some((flares.iter().map(|(id, _)| *id).collect(), settings)) +} + +/// The settings `fields` give a flare: each option, with a count of 0 when its checkbox is off. +fn shown(fields: &Map) -> Map { + let get = |key: &str, default: f64| fields.get(key).and_then(Value::as_f64).unwrap_or(default); + let on = |key: &str| fields.get(key).and_then(Value::as_bool) != Some(false); + FLARE_OPTIONS + .iter() + .map(|&(key, default, ..)| { + let v = match key { + "rays" if !on("raysOn") => 0.0, + "rings" if !on("ringsOn") => 0.0, + "rays" | "rings" => get(key, default).round(), + _ => get(key, default), + }; + (key.to_string(), json!(v)) + }) + .collect() +} + +/// `shape.editFlare`'s params for the selected flares: the settings changed since the dialog opened. +fn edit_params(d: &Dialog) -> Option { + let ids = d.fields.get("flares")?.clone(); + let start = d.fields.get("shown").and_then(Value::as_object).cloned().unwrap_or_default(); + let mut params = json!({ "ids": ids }); + for (key, v) in shown(&d.fields) { + if start.get(&key) != Some(&v) { + params[key.as_str()] = if matches!(key.as_str(), "rays" | "rings") { json!(v.as_f64().unwrap_or(0.0) as u64) } else { v }; + } + } + Some(params) +} + /// A row for option `key`, kept within its range: a distance in `unit`, else a number. fn field(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit, (key, label): (&str, &str)) { let Some(&(_, default, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return }; @@ -119,8 +192,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// A click-created flare previews at that original click; toolbar options draw no artwork. +/// A click-created flare previews at that original click, and the selected flares preview with the +/// settings changed; toolbar options draw no artwork. fn preview_command(app: &VectorcraftApp, d: &Dialog) -> Option<(String, Value)> { + if let Some(params) = edit_params(d) { + return Some(("shape.editFlare".into(), params)); + } let at = Point::new(d.fields.get("x")?.as_f64().filter(|v| v.is_finite())?, d.fields.get("y")?.as_f64().filter(|v| v.is_finite())?); // Use the same clamping and whole-count conversion as accepted tool settings. let mut tool = vectorcraft_tools::create("flare"); @@ -143,8 +220,16 @@ fn reset(_: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { Ok(()) } -/// OK: set the tool's options; opened by a click, draw a flare there with them. +/// OK: set the tool's options; opened by a click, draw a flare there with them. Opened for the +/// selected flares, draw them again with the settings changed, leaving the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + if let Some(params) = edit_params(d) { + return if d.fields.contains_key(form::PREVIEWED) { + form::commit_preview(app, "shape.editFlare", params) + } else { + run_and_close(app, "shape.editFlare", params) + }; + } let command = preview_command(app, d); if command.is_none() && (d.fields.contains_key("x") || d.fields.contains_key("y") || d.fields.contains_key(form::PREVIEWED)) { return Err("Flare click coordinates must be finite numbers".into()); @@ -321,6 +406,41 @@ mod tests { assert_eq!(app.session.tool_options_of("flare"), before); } + /// With a flare selected, the toolbar's Flare Tool Options show its settings, and OK draws it + /// again with the settings changed, as one undo step, leaving the tool's options. + #[test] + fn with_a_flare_selected_the_options_show_its_settings_and_ok_draws_it_again() { + let mut app = app(); + let flare = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 0, "rings": 4, "x2": 200, "y2": 0, "largest": 80, "seed": 5}); + app.run("shape.flare", flare).unwrap(); + app.run("object.move", json!({"dx": 30, "dy": 0})).unwrap(); + let options = app.session.tool_options_of("flare"); + app.run("tool.options", json!({"tool": "flare"})).unwrap(); + painted(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + let shown = (d.f64("diameter", 0.0), d.bool("raysOn"), d.f64("rays", 0.0), d.f64("rings", 0.0), d.f64("largest", 0.0)); + assert_eq!(shown, (60.0, false, 15.0, 4.0, 80.0)); + assert!((d.f64("pathLength", 0.0) - 200.0).abs() < 1e-9 && (d.f64("direction", 0.0) - 90.0).abs() < 1e-9); + d.fields.insert("rings".into(), json!(7)); + d.fields.insert("raysOn".into(), json!(true)); + let depth = app.session.doc().unwrap().history.undo.len(); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1); + let parts = flare_parts(&app); + assert_eq!((parts.iter().filter(|p| *p == "Ring").count(), parts.iter().any(|p| p == "Rays")), (7, true), "{parts:?}"); + // Still where it was moved to. + let doc = &app.session.doc().unwrap().doc; + let id = app.session.doc().unwrap().selection.objects[0]; + assert!(vectorcraft_engine::flare_settings(doc, id).unwrap().center().unwrap().distance(Point::new(230.0, 200.0)) < 1e-9); + assert_eq!(app.session.tool_options_of("flare"), options); + // With nothing selected, the dialog shows the tool's options again. + app.run("select.none", json!({})).unwrap(); + app.run("tool.options", json!({"tool": "flare"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("diameter", 0.0), d.fields.contains_key("flares")), (100.0, false)); + } + #[test] fn ui_dialog_reset_puts_the_defaults_back_and_keeps_where_a_click_opened_it() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 78fdd8bdd1..aa793afef2 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -280,6 +280,7 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { variation: (0.0, 100.0), }; varied(ui, d, &roundness, &Variation::ALL); + tip_preview(ui, d, roundness.range.0); size_rows(ui, d, &Variation::ALL); } else { if d.fields.contains_key("angle") { @@ -291,7 +292,7 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } } if d.str("tool") == "blobBrush" { - blob_tip_preview(ui, d); + tip_preview(ui, d, 0.0); } // The Eraser's Size rows are above. if !eraser && d.fields.contains_key("sizeMode") { @@ -331,26 +332,26 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// Side of the Blob Brush tip preview's square, in points. +/// Side of the Blob Brush's and the Eraser's tip preview square, in points. const TIP_PREVIEW: f32 = 64.0; -/// Half the length of the Blob Brush tip in its preview, in points. +/// Half the length of the tip in its preview, in points. const TIP_LONG: f32 = 18.0; /// How far from a Roundness dot of the tip preview a press still takes the dot, in points. const TIP_DOT_REACH: f32 = 8.0; -/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness, a line with an -/// arrowhead along its long axis and a black dot at each end of its short axis, and beside it three -/// dabs of the tip, the middle one darker. A click or a drag that starts on a dot sets the -/// Roundness from the pointer's distance from the center along the short axis -/// ([`blob_tip_roundness_at`]) until the release, inside the square or out of it, and gives the +/// The Blob Brush's and the Eraser's tip preview: a square with the tip at its Angle and +/// Roundness, a line with an arrowhead along its long axis and a black dot at each end of its short +/// axis, and beside it three dabs of the tip, the middle one darker. A click or a drag that starts +/// on a dot sets the Roundness from the pointer's distance from the center along the short axis +/// ([`tip_roundness_at`]) until the release, inside the square or out of it, and gives the /// Roundness slider the keyboard focus. A click or a drag that starts anywhere else in the square /// points the Angle at the pointer and gives the Angle slider the focus. Screen readers get the /// square as the Angle slider and then the Roundness slider, and their keys step the Angle within -/// -180° to 180° and the Roundness within 0% to 100% as a dialog slider's do +/// -180° to 180° and the Roundness within `min_roundness` to 100% as a dialog slider's do /// ([`widgets::stepped_area`]). -fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { +fn tip_preview(ui: &mut egui::Ui, d: &mut Dialog, min_roundness: f64) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(egui::vec2(CONTENT_W, TIP_PREVIEW), egui::Sense::hover()); let square = egui::Rect::from_min_size(rect.min, egui::vec2(TIP_PREVIEW, TIP_PREVIEW)); @@ -359,7 +360,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { // Whether the press that started this click or drag was on a dot: it is kept until the release. let on_dot = response.id.with("on-dot"); let near_dot = |p: egui::Pos2, d: &Dialog| { - blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH) + tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH) }; let mut started = ui.data(|m| m.get_temp::(on_dot)); if started.is_none() && response.is_pointer_button_down_on() { @@ -383,7 +384,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { if let Some((p, _)) = widgets::pointer_phase(&response) { let delta = p - center; if dot_drag { - d.fields.insert("roundness".into(), json!(blob_tip_roundness_at(delta, d.f64("angle", 0.0)))); + d.fields.insert("roundness".into(), json!(tip_roundness_at(delta, d.f64("angle", 0.0), min_roundness))); } else if delta.length_sq() > 1.0 { d.fields.insert("angle".into(), json!(f64::from((-delta.y).atan2(delta.x)).to_degrees().round())); } @@ -406,13 +407,13 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { if dot_drag && (response.drag_started() || response.clicked()) { widgets::focus_by_pointer(ui, roundness.id); } - let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), 0.0..=100.0, "%", 0); + let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), min_roundness..=100.0, "%", 0); if let Some(r) = widgets::stepped_area(ui, &roundness, tl!("Roundness"), Some(shown)) { d.fields.insert("roundness".into(), json!(r)); } - let (u, v) = blob_tip_axes(d.f64("angle", 0.0)); + let (u, v) = tip_axes(d.f64("angle", 0.0)); let long = TIP_LONG; - let short = long * blob_tip_short_ratio(d.f64("roundness", 100.0)); + let short = long * tip_short_ratio(d.f64("roundness", 100.0)); let dab = |center: egui::Pos2, color: egui::Color32| { let points = (0..32) .map(|i| { @@ -427,7 +428,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { let arrowhead = vec![center + u * 28.0, center + u * 22.0 + v * 3.0, center + u * 22.0 - v * 3.0]; painter.add(egui::Shape::convex_polygon(arrowhead, t.accent, egui::Stroke::NONE)); // Black with a white rim, so a dot shows on the tip and on the square in either theme. - for dot in blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) { + for dot in tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) { painter.circle(dot, 3.0, egui::Color32::BLACK, egui::Stroke::new(1.0, egui::Color32::WHITE)); } let strip = square.right() + 2.5 * long; @@ -438,7 +439,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { /// The tip preview's long axis on screen at Angle `angle` (degrees, y down: a positive angle tilts /// it up to the right), and its short axis. -fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) { +fn tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) { let a = angle.clamp(-180.0, 180.0).to_radians(); let u = egui::vec2(a.cos() as f32, -a.sin() as f32); (u, egui::vec2(-u.y, u.x)) @@ -446,23 +447,23 @@ fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) { /// The two Roundness dots of the tip preview centered on `center`: the ends of the tip's short /// axis at Angle `angle` and Roundness `roundness`. -fn blob_tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] { - let (_, v) = blob_tip_axes(angle); - let short = v * (TIP_LONG * blob_tip_short_ratio(roundness)); +fn tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] { + let (_, v) = tip_axes(angle); + let short = v * (TIP_LONG * tip_short_ratio(roundness)); [center + short, center - short] } -/// The Roundness, in whole percent from 0 to 100, that a dot of the tip preview dragged to `offset` -/// from the preview's center gives at Angle `angle`: the distance along the tip's short axis, on -/// either side of the center, as a percentage of half the tip's length. -fn blob_tip_roundness_at(offset: egui::Vec2, angle: f64) -> f64 { - let (_, v) = blob_tip_axes(angle); - (f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(0.0, 100.0) +/// The Roundness, in whole percent from `min` to 100, that a dot of the tip preview dragged to +/// `offset` from the preview's center gives at Angle `angle`: the distance along the tip's short +/// axis, on either side of the center, as a percentage of half the tip's length. +fn tip_roundness_at(offset: egui::Vec2, angle: f64, min: f64) -> f64 { + let (_, v) = tip_axes(angle); + (f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(min, 100.0) } /// The preview tip's short axis as a fraction of its long axis: Roundness in percent, with 0 -/// percent drawn as 0.1 percent, the minimum the brush draws with. -fn blob_tip_short_ratio(roundness: f64) -> f32 { +/// percent drawn as 0.1 percent, the minimum the Blob Brush draws with. +fn tip_short_ratio(roundness: f64) -> f32 { (roundness.clamp(0.0, 100.0) as f32 / 100.0).max(0.001) } diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 6ec010a8bd..e324bbbd45 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -50,7 +50,12 @@ fn a_refused_fidelity_keeps_the_dialog_open() { fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] { let drawn = vectorcraft_tools::draw2::blob_tip(0.0, roundness).as_coeffs()[3] as f32; - assert!((blob_tip_short_ratio(roundness) - drawn).abs() < 1e-6, "roundness {roundness}: drawn {drawn}"); + assert!((tip_short_ratio(roundness) - drawn).abs() < 1e-6, "roundness {roundness}: drawn {drawn}"); + } + // The Eraser's Roundness runs from 1% to 100%, where its tip and the Blob Brush's are the same. + for roundness in [1.0, 2.0, 50.0, 100.0] { + let drawn = vectorcraft_tools::draw2::eraser_tip(0.0, roundness).as_coeffs()[3] as f32; + assert!((tip_short_ratio(roundness) - drawn).abs() < 1e-6, "Eraser roundness {roundness}: drawn {drawn}"); } } @@ -61,23 +66,35 @@ fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { #[test] fn a_roundness_dot_sets_its_distance_along_the_short_axis() { for angle in [0.0, 30.0, 90.0, -135.0, 180.0] { - let (u, v) = blob_tip_axes(angle); + let (u, v) = tip_axes(angle); for (along, want) in [(0.0, 0.0), (4.5, 25.0), (-9.0, 50.0), (18.0, 100.0), (-18.0, 100.0), (40.0, 100.0), (-400.0, 100.0)] { for sideways in [0.0, 7.0, -30.0] { - assert_eq!(blob_tip_roundness_at(v * along + u * sideways, angle), want, "angle {angle}, {along} along, {sideways} sideways"); + assert_eq!(tip_roundness_at(v * along + u * sideways, angle, 0.0), want, "angle {angle}, {along} along, {sideways} sideways"); } } let center = egui::pos2(32.0, 32.0); for roundness in [0.0, 1.0, 37.0, 50.0, 99.0, 100.0] { - let [a, b] = blob_tip_dots(center, angle, roundness); + let [a, b] = tip_dots(center, angle, roundness); assert!(((a - center) + (b - center)).length() < 1e-4, "the dots face each other across the center"); for dot in [a, b] { - assert_eq!(blob_tip_roundness_at(dot - center, angle), roundness, "angle {angle}"); + assert_eq!(tip_roundness_at(dot - center, angle, 0.0), roundness, "angle {angle}"); } } } } +/// With the Eraser's 1% minimum, a Roundness dot dragged to the center or near it gives 1%, and +/// any farther distance gives the same Roundness as with no minimum. +#[test] +fn a_roundness_dot_keeps_the_eraser_at_one_percent_or_more() { + for angle in [0.0, 45.0, -90.0] { + let (u, v) = tip_axes(angle); + for (along, want) in [(0.0, 1.0), (0.05, 1.0), (-0.1, 1.0), (0.18, 1.0), (0.36, 2.0), (-9.0, 50.0), (30.0, 100.0)] { + assert_eq!(tip_roundness_at(v * along + u * 5.0, angle, 1.0), want, "angle {angle}, {along} along"); + } + } +} + /// The labels the open dialog paints. fn painted(app: &mut VectorcraftApp) -> String { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index c5acd64e18..950f28d6e4 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -26,8 +26,7 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 // Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop. ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK); }); - let pass = ctx.cumulative_pass_nr(); - ctx.data_mut(|d| d.insert_temp(drawn_pass_id(), pass)); + let opened = opened(ctx, id); let shown = egui::Window::new(title) .id(id) .order(egui::Order::Foreground) @@ -39,7 +38,7 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .show(ctx, |ui| { // Just opened: what scrolls in the window starts at its top, wherever it was left when // the window last closed. - if opened(ctx, id) { + if opened { ctx.data_mut(|m| { m.insert_temp(id.with(TOP_ROWS_KEY), true); m.insert_temp(id.with(TOP_WHOLE_KEY), true); @@ -76,16 +75,18 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 shown.inner } -/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before, -/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard -/// Shortcuts). The window under it keeps where it was scrolled to. +/// Mark the modal window drawn next in this pass as opened over the windows drawn in the pass +/// before (a dialog and any alert of its own), which it hides until it closes and shows them again +/// (Import Shortcut Set over Keyboard Shortcuts). The windows under it keep where they were +/// scrolled to. pub(crate) fn over_parent(ctx: &egui::Context) { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass)); } -/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before, -/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]). +/// Record that modal window `id` is drawn in this pass, and return whether it opened in it: it was +/// not drawn in the pass before, and none of the windows drawn in the pass before was one opened +/// over it ([`over_parent`]). fn opened(ctx: &egui::Context, id: Id) -> bool { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|m| { @@ -101,27 +102,32 @@ fn opened(ctx: &egui::Context, id: Id) -> bool { let before: Vec = prev.iter().copied().filter(|&other| other != id).collect(); now.push(id); m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev)); + // Only the window drawn next after `over_parent` is opened over the others. + let over = m.remove_temp::(Id::unique(OVER_KEY)) == Some(pass); let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass); if last != u64::MAX && last.saturating_add(1) >= pass { return false; } // Shown again as the window opened over it closed. - if before.iter().any(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { + if before.iter().any(|under| m.get_temp::>(under.with(HOLDS_KEY)).is_some_and(|held| held.contains(&id))) { return false; } - // Opened over the window drawn last in the pass before, it holds that one; otherwise none. - match before.last().copied().filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { - Some(under) => { - m.insert_temp(id.with(HOLDS_KEY), under); - } - None => { - m.remove::(id.with(HOLDS_KEY)); - } + // Opened over the windows drawn in the pass before, it holds them; otherwise none. + if over && !before.is_empty() { + m.insert_temp(id.with(HOLDS_KEY), before); + } else { + m.remove::>(id.with(HOLDS_KEY)); } true }) } +/// The windows modal window `id` was opened over and hides ([`over_parent`]). +#[cfg(test)] +fn holds(ctx: &egui::Context, id: Id) -> Vec { + ctx.data(|m| m.get_temp::>(id.with(HOLDS_KEY))).unwrap_or_default() +} + /// The room for the contents of a modal window with `margin` inside its frame. fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 { (ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO) @@ -133,15 +139,11 @@ pub(crate) fn backdrop() -> egui::LayerId { egui::LayerId::new(egui::Order::Middle, Id::unique("modal-dim")) } -/// The key of the pass in which [`show_at`] last drew a modal window. -fn drawn_pass_id() -> Id { - Id::unique("modal-drawn-pass") -} - /// Whether [`show_at`] drew a modal window in this pass. Unlike the backdrop's visibility, which /// also counts the last pass, it is false in the pass after the window closes. pub(crate) fn drawn_this_pass(ctx: &egui::Context) -> bool { - ctx.data(|d| d.get_temp::(drawn_pass_id())) == Some(ctx.cumulative_pass_nr()) + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.get_temp_mut_or::<(u64, Vec, Vec)>(Id::unique(LAST_KEY), (u64::MAX, vec![], vec![])).0 == pass) } /// The dialog's heading, which also moves the window ([`drag_band`]). @@ -197,9 +199,10 @@ const SHOWN_KEY: &str = "modal-shown"; const TOP_ROWS_KEY: &str = "modal-top-rows"; const TOP_WHOLE_KEY: &str = "modal-top-whole"; /// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass -/// and of those drawn in the pass before it (`LAST_KEY`), and the pass -/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`). -/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`). +/// and of those drawn in the pass before it (`LAST_KEY`, which [`drawn_this_pass`] also reads), and +/// the pass in which the window drawn next was marked as opened over others ([`over_parent`], +/// `OVER_KEY`, taken by that window). Under a modal window's id: the windows it was opened over and +/// hides (`HOLDS_KEY`). const LAST_KEY: &str = "modal-last"; const OVER_KEY: &str = "modal-over"; const HOLDS_KEY: &str = "modal-holds"; @@ -446,24 +449,36 @@ mod tests { #[test] fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() { // As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it - // did not close. A window that another replaced did close. Either may have shown an alert - // of its own, drawn after it in the same passes. + // did not close. A window that another replaced did close. Any of them may have shown an + // alert of its own, drawn after it in the same passes: A before B or C opens, or B or C. let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)]; + let id = |name: &str| Id::unique(("modal-reopen-test", name)); let mut wrong = vec![]; for in_rows in [false, true] { - for (other, kept) in others { - let ctx = egui::Context::default(); - crate::theme::apply(&ctx, Default::default()); - let mut time = 0.0; - first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); - if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { - wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); - } - if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { - wrong.push(format!("rows {in_rows}: {other:?} does not open at its top")); - } - if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { - wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); + for lead in [&["A"][..], &["A", "Alert"][..]] { + for (other, kept) in others { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); + if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { + wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); + } + first_row_seen(&ctx, lead, in_rows, vec![], &mut time, 4); + if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { + wrong.push(format!("rows {in_rows}: after {lead:?}, {other:?} does not open at its top")); + } + // Only the window opened over A holds it; an alert drawn after that window holds none. + let held: Vec> = other.iter().map(|&name| holds(&ctx, id(name))).collect(); + let want: Vec> = + other.iter().map(|&name| if name.starts_with("over ") { lead.iter().map(|&l| id(l)).collect() } else { vec![] }).collect(); + if held != want { + wrong.push(format!("rows {in_rows}: after {lead:?}, {other:?} hold {held:?}, not {want:?}")); + } + if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { + let state = if kept { "is not" } else { "is still" }; + wrong.push(format!("rows {in_rows}: after {lead:?} and {other:?}, A {state} where it was scrolled to")); + } } } } diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs new file mode 100644 index 0000000000..0ee49a194a --- /dev/null +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -0,0 +1,896 @@ +//! Object › Create Object Mosaic…: the selected image's Current Size, the mosaic's New Size, Tile +//! Spacing and Number of Tiles, Constrain Ratio (Width or Height), Result (Color or Grayscale), +//! Resize Using Percentages, Delete Raster and Use Ratio. OK runs `object.createObjectMosaic` as one +//! undo step. +//! +//! Fields: `width`, `height` (pt, or percentages of the image's size with `percentages`), +//! `spacingX`, `spacingY` (pt), `columns`, `rows`, `lock` (Constrain Ratio on), `constrain` +//! (`width` | `height`: the side Constrain Ratio and Use Ratio keep), `gray`, `percentages` and +//! `deleteRaster`. `__imageW` and `__imageH` hold the image's size (pt), read again from the +//! selected image each frame, before `ui.dialog.set` sets fields and on OK; `__noImage` is true +//! while no image is selected. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; + +use super::{DialogSpec, form}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Create Object Mosaic. +pub const KIND: &str = "objectMosaic"; + +/// The command the dialog runs. +pub const COMMAND: &str = "object.createObjectMosaic"; + +/// Width of the label column. +const LABEL_W: f32 = 112.0; + +/// Width of a size or count field. +const FIELD_W: f32 = 76.0; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Create Object Mosaic").into(), body, confirm, min_width: 360.0, ..DialogSpec::FORM }; + +/// The size (pt) of the first selected image, which the mosaic is made from. +fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> { + let st = app.session.active()?; + let node = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).find(|n| matches!(n.kind, NodeKind::Image(_)))?; + let b = node.geometric_bounds()?; + Some((b.width(), b.height())) +} + +/// Open the dialog on the selected image, with the values `given` holds (the menu item's params, or +/// a caller's `object.createObjectMosaic` params, its Use Ratio applied to the counts) and the +/// command's defaults for the rest. With no image selected, or with params the command refuses, +/// nothing opens and the error says why. +pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result { + let Some((w, h)) = image_size(app) else { return Err("select an image".into()) }; + let none = json!({}); + let given = if given.is_null() { &none } else { given }; + app.session.check_params(COMMAND, given).map_err(|e| e.to_string())?; + let (cols, rows) = vectorcraft_engine::cmd::mosaic_counts(&app.session, given).map_err(|e| e.to_string())?; + let n = |key: &str, d: f64| given.get(key).and_then(Value::as_f64).unwrap_or(d); + let b = |key: &str| given.get(key).and_then(Value::as_bool).unwrap_or(false); + let pct = b("percentages"); + // The new size starts at the image's, within the sizes the command takes (0.1 to 1,000,000 pt). + let (base_w, base_h) = if pct { (100.0, 100.0) } else { (w.clamp(0.1, 1.0e6), h.clamp(0.1, 1.0e6)) }; + let named = |key: &str| given.get(key).and_then(Value::as_str).filter(|s| matches!(*s, "width" | "height")); + let constrain = named("constrain"); + // The side the dialog keeps: Constrain Ratio's, else the one Use Ratio names. + let side = constrain.or(named("useRatio")).unwrap_or("width"); + let fields = json!({ + "width": n("width", base_w), "height": n("height", base_h), "spacingX": n("spacingX", 0.0), "spacingY": n("spacingY", 0.0), + "columns": cols, "rows": rows, + "lock": constrain.is_some(), "constrain": side, "gray": b("gray"), "percentages": pct, + "deleteRaster": b("deleteRaster"), "__imageW": w, "__imageH": h, + }); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(json!({ "dialog": KIND })) +} + +/// The field that is true while no image is selected. +const NO_IMAGE: &str = "__noImage"; + +/// What the dialog shows when Resize Using Percentages is switched with no image selected. +const NO_IMAGE_WHY: &str = "select an image"; + +/// The selected image's size `size` (from [`image_size`]) read into the dialog, so New Size is +/// converted and constrained against the image as it is now, also after it was scaled while the +/// dialog was open. With no image selected the last size read stays and `__noImage` is set. +fn read_image(size: Option<(f64, f64)>, d: &mut Dialog) { + let Some((w, h)) = size else { + d.fields.insert(NO_IMAGE.into(), json!(true)); + return; + }; + if d.fields.remove(NO_IMAGE).is_some() && d.str(form::REFUSED) == NO_IMAGE_WHY { + d.fields.remove(form::REFUSED); + } + d.fields.insert("__imageW".into(), json!(w)); + d.fields.insert("__imageH".into(), json!(h)); +} + +/// [`read_image`] on the open dialog when it is this one. `ui.dialog.set` runs it before it sets +/// any field. +pub(crate) fn refresh(app: &mut VectorcraftApp) { + let size = image_size(app); + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == KIND) { + read_image(size, d); + } +} + +/// The image's size (pt) the dialog holds. +fn image(d: &Dialog) -> (f64, f64) { + (d.f64("__imageW", 1.0).max(1e-9), d.f64("__imageH", 1.0).max(1e-9)) +} + +/// Whether Constrain Ratio and Use Ratio keep the width (else the height). +fn keeps_width(d: &Dialog) -> bool { + d.str("constrain") != "height" +} + +/// With Constrain Ratio on, the size field that follows the kept side. +fn follower(d: &Dialog) -> Option<&'static str> { + d.bool("lock").then(|| if keeps_width(d) { "height" } else { "width" }) +} + +/// The new sizes the command takes, in points or percentages (`object.createObjectMosaic`). +const SIZE_RANGE: std::ops::RangeInclusive = 0.1..=1.0e6; + +/// With Constrain Ratio on, the side that follows set from the side that leads, in the image's +/// proportions. A size `ui.dialog.set` gave the following side that the command refuses stays, +/// for OK to report. +fn follow_ratio(d: &mut Dialog) { + let Some((key, v)) = derived(d) else { return }; + if d.bool(&kept(key)) { + if !takes(d, key) { + return; + } + d.fields.remove(&kept(key)); + } + d.fields.insert(key.into(), json!(v)); +} + +/// The field that is true while size field `key` holds a value `ui.dialog.set` gave and the +/// command refuses. +fn kept(key: &str) -> String { + format!("__kept.{key}") +} + +/// Whether the command takes size field `key` as it is: a number from 0.1 to 1,000,000. +fn takes(d: &Dialog, key: &str) -> bool { + number(d, key, 0.0).as_f64().is_some_and(|x| SIZE_RANGE.contains(&x)) +} + +/// `ui.dialog.set` of `field`: a new size the command refuses (not a number, or outside 0.1 to +/// 1,000,000) stays in its field while it is refused, also on the side Constrain Ratio sets, instead +/// of being replaced by the size worked out from the kept side. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if !matches!(field, "width" | "height") { + return; + } + if takes(d, field) { + d.fields.remove(&kept(field)); + } else { + d.fields.insert(kept(field), json!(true)); + } +} + +/// With Constrain Ratio on, the side that follows and the size it gets from the side that leads. +fn derived(d: &Dialog) -> Option<(&'static str, f64)> { + let key = follower(d)?; + let (iw, ih) = image(d); + let pct = in_percentages(d); + Some(if key == "height" { + let w = d.f64("width", 0.0); + (key, if pct { w } else { w * ih / iw }) + } else { + let h = d.f64("height", 0.0); + (key, if pct { h } else { h * iw / ih }) + }) +} + +/// Resize Using Percentages turned on or off: the new size shown the other way, so it stays the +/// same size. When a size field does not hold a number, or a size the command takes (all but the +/// side Constrain Ratio sets) falls outside what the command accepts either as it is or the other +/// way, the fields and the mode stay as they are and the dialog shows why. With no image selected, nothing changes and +/// the dialog asks for one. +fn switch_percentages(d: &mut Dialog, on: bool) { + if d.bool(NO_IMAGE) { + d.fields.insert(form::REFUSED.into(), json!(NO_IMAGE_WHY)); + return; + } + let (iw, ih) = image(d); + let size = |key: &str| number(d, key, 100.0).as_f64().ok_or_else(|| format!("`{key}` must be a number (got {})", d.str(key))); + let (w, h) = match (size("width"), size("height")) { + (Ok(w), Ok(h)) => (w, h), + (Err(why), _) | (_, Err(why)) => { + d.fields.insert(form::REFUSED.into(), json!(why)); + return; + } + }; + let skip = follower(d); + let checked = |key: &str| skip != Some(key) || d.bool(&kept(key)); + let refused = |w: f64, h: f64| { + let (key, v) = [("width", w), ("height", h)].into_iter().find(|(k, v)| checked(k) && !SIZE_RANGE.contains(v))?; + Some(format!("`{key}` must be between {} and {} (got {v})", SIZE_RANGE.start(), SIZE_RANGE.end())) + }; + // A size the command refuses as it is stays refused, even when it falls in range the other way. + let converted = if on { (w / iw * 100.0, h / ih * 100.0) } else { (iw * w / 100.0, ih * h / 100.0) }; + if let Some(why) = refused(w, h).or_else(|| refused(converted.0, converted.1)) { + d.fields.insert(form::REFUSED.into(), json!(why)); + return; + } + let (w, h) = converted; + d.fields.remove(form::REFUSED); + d.fields.remove(&kept("percentages")); + d.fields.insert("width".into(), json!(w)); + d.fields.insert("height".into(), json!(h)); + d.fields.insert("percentages".into(), json!(on)); +} + +/// Whether the new size fields hold percentages: Resize Using Percentages, or while that field holds +/// a value that is not true or false, the mode it held before that value was set. +fn in_percentages(d: &Dialog) -> bool { + match d.fields.get("percentages") { + Some(Value::Bool(on)) => *on, + Some(_) => d.bool(&kept("percentages")), + None => false, + } +} + +/// `ui.dialog.set` of `percentages`: true or false switches the new size as the checkbox does, and +/// replaces a value that is not true or false; null is false. Another value is kept as it is, and +/// the command refuses it on OK. +pub(super) fn set_percentages(d: &mut Dialog, value: &Value) { + let mode = in_percentages(d); + // The command reads null as the field left out, which is off. + match if value.is_null() { Some(false) } else { value.as_bool() } { + Some(on) if on != mode => switch_percentages(d, on), + Some(on) => { + d.fields.remove(&kept("percentages")); + d.fields.insert("percentages".into(), json!(on)); + } + None => { + d.fields.insert(kept("percentages"), json!(mode)); + d.fields.insert("percentages".into(), value.clone()); + } + } +} + +/// Use Ratio: the count on the kept side stays and the other makes the tiles square, as the +/// command counts them for the fields as they are (Constrain Ratio's side, the new size and the +/// spacing). +fn use_ratio(app: &VectorcraftApp, d: &mut Dialog) { + let mut p = params(d); + p["useRatio"] = json!(if keeps_width(d) { "width" } else { "height" }); + match vectorcraft_engine::cmd::mosaic_counts(&app.session, &p) { + Ok((cols, rows)) => { + d.fields.remove(form::REFUSED); + d.fields.insert("columns".into(), json!(cols)); + d.fields.insert("rows".into(), json!(rows)); + } + Err(e) => form::note_refusal(d, &e), + } +} + +/// Field `key` as `object.createObjectMosaic` takes it: a number (text with a unit, as +/// `ui.dialog.set` may give it, read in points), `default` when the field is missing, and any other +/// value as it is, for the command to refuse. +fn number(d: &Dialog, key: &str, default: f64) -> Value { + match d.fields.get(key) { + None => json!(default), + Some(Value::String(s)) => vectorcraft_doc::Unit::Points.parse(s).map_or_else(|| json!(s), |v| json!(v)), + Some(v) => v.clone(), + } +} + +/// Field `key` as the command takes an on/off value: false when the field is missing, and any +/// other value as it is, for the command to refuse one that is not true or false. +fn switch(d: &Dialog, key: &str) -> Value { + d.fields.get(key).cloned().unwrap_or(json!(false)) +} + +/// `constrain` as the command takes it: null with Constrain Ratio off, else the side the field +/// holds (the width when it holds none), and any other value as it is, for the command to refuse. +fn constrained_side(d: &Dialog) -> Value { + if !d.bool("lock") { + return Value::Null; + } + match d.fields.get("constrain") { + None | Some(Value::Null) => json!("width"), + Some(v) => v.clone(), + } +} + +/// `object.createObjectMosaic` parameters from the fields. With Constrain Ratio on, the side it +/// sets is left out while it holds the size Constrain Ratio gives it: the command works it out from +/// the kept side and grows both in proportion to its 0.1 pt minimum. Any other value set on that +/// side, and a refused value `ui.dialog.set` gave it even when it equals that size, is passed on for +/// the command to check. +fn params(d: &Dialog) -> Value { + let mut p = json!({ + "columns": number(d, "columns", 10.0), "rows": number(d, "rows", 10.0), + "width": number(d, "width", 100.0), "height": number(d, "height", 100.0), "percentages": switch(d, "percentages"), + "constrain": constrained_side(d), + "spacingX": number(d, "spacingX", 0.0), "spacingY": number(d, "spacingY", 0.0), + "gray": switch(d, "gray"), "deleteRaster": switch(d, "deleteRaster"), + }); + if let (Some((key, v)), Some(o)) = (derived(d), p.as_object_mut()) + && !d.bool(&kept(key)) + && o.get(key).and_then(Value::as_f64).is_some_and(|x| x == v) + { + o.remove(key); + } + p +} + +/// A Width and a Height field for `keys`: lengths in `unit` of at least `least` points, or +/// percentages with `pct`, up to 1,000,000. With `follows`, the field of that key is grayed (Constrain Ratio sets it). +fn pair(ui: &mut egui::Ui, d: &mut Dialog, keys: [&str; 2], unit: vectorcraft_doc::Unit, (pct, least): (bool, f64), follows: Option<&str>) { + for (key, label) in keys.into_iter().zip([tl!("Width:"), tl!("Height:")]) { + widgets::dim_label(ui, label); + ui.add_enabled_ui(follows != Some(key), |ui| { + if pct { + if let Some(v) = widgets::spin_plain(ui, ("mosaic", key), d.f64(key, 100.0), "%", 2, FIELD_W, 1.0, 0.1, &[]) { + d.fields.insert(key.into(), json!(v.min(*SIZE_RANGE.end()))); + } + } else { + form::length_within(ui, d, key, unit, FIELD_W, Some(least..=1.0e6)); + } + }); + } +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + read_image(image_size(app), d); + let (iw, ih) = image(d); + widgets::label_row(ui, tl!("Current Size:"), LABEL_W, |ui| { + widgets::dim_label(ui, tl!("Width:")); + widgets::dim_name(ui, &unit.format(iw)); + widgets::dim_label(ui, tl!("Height:")); + widgets::dim_name(ui, &unit.format(ih)); + }); + ui.add_space(4.0); + let follows = follower(d); + let pct = in_percentages(d); + widgets::label_row(ui, tl!("New Size:"), LABEL_W, |ui| pair(ui, d, ["width", "height"], unit, (pct, 0.1), follows)); + follow_ratio(d); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Tile Spacing:"), LABEL_W, |ui| pair(ui, d, ["spacingX", "spacingY"], unit, (false, 0.0), None)); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Number of Tiles:"), LABEL_W, |ui| { + for (key, label) in [("columns", tl!("Width:")), ("rows", tl!("Height:"))] { + widgets::dim_label(ui, label); + if let Some(v) = widgets::spin_plain(ui, ("mosaic", key), d.f64(key, 10.0), "", 0, FIELD_W, 1.0, 1.0, &[]) { + d.fields.insert(key.into(), json!(v.round().clamp(1.0, 1000.0))); + } + } + }); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Constrain Ratio:"), LABEL_W, |ui| { + form::check(ui, d, "lock", tl!("Constrain Width and Height Proportions")); + let width = keeps_width(d); + if widgets::radio(ui, tl!("Width"), width, true) { + d.fields.insert("constrain".into(), json!("width")); + } + if widgets::radio(ui, tl!("Height"), !width, true) { + d.fields.insert("constrain".into(), json!("height")); + } + }); + follow_ratio(d); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Result:"), LABEL_W, |ui| { + let gray = d.bool("gray"); + if widgets::radio(ui, tl!("Color"), !gray, true) { + d.fields.insert("gray".into(), json!(false)); + } + if widgets::radio(ui, tl!("Grayscale"), gray, true) { + d.fields.insert("gray".into(), json!(true)); + } + }); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Options:"), LABEL_W, |ui| { + ui.vertical(|ui| { + if widgets::check(ui, tl!("Resize Using Percentages"), pct, true) { + switch_percentages(d, !pct); + } + form::check(ui, d, "deleteRaster", tl!("Delete Raster")); + }); + }); + if let Some(why) = d.fields.get(form::REFUSED).and_then(Value::as_str) { + ui.add_space(4.0); + ui.add(egui::Label::new(egui::RichText::new(why).color(Tokens::get(ui.ctx()).warning)).wrap()); + } + ui.add_space(6.0); + if widgets::flat_button(ui, tl!("Use Ratio"), 96.0).clicked() { + use_ratio(app, d); + } + false +} + +/// OK: the new size worked out against the image's size as it is now, as a frame would show it. +/// A Constrain Ratio (`lock`) that is not true or false is refused, and the dialog stays open. The +/// dialog also stays open with its fields when the command refuses them, as [`form::commit_preview`] +/// does. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get("lock").is_some_and(|v| !v.is_boolean() && !v.is_null()) { + return Err("`lock` must be true or false".into()); + } + let mut d = d.clone(); + read_image(image_size(app), &mut d); + follow_ratio(&mut d); + let r = app.run(COMMAND, params(&d)); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// A frame of the open dialog → the texts painted. The dialog measures itself on its first + /// frame, so a fresh context needs two. + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.shapes.iter().filter_map(|s| if let egui::epaint::Shape::Text(t) = &s.shape { Some(t.galley.text().to_string()) } else { None }).collect() + } + + fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + } + + /// A tile count the dialog holds. + fn count(d: &Dialog, key: &str) -> u32 { + d.f64(key, 0.0) as u32 + } + + /// An app with a 100 × 50 pt embedded image selected. + fn app_with_image() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("object.rasterize", json!({"ppi": 72})).unwrap(); + app + } + + /// The mosaic group's size and tile count. + fn mosaic(app: &VectorcraftApp) -> Option<(f64, f64, usize)> { + let mut found = None; + app.session.active()?.doc.walk(|n| { + if n.name.as_deref() == Some("Object Mosaic") { + let b = n.geometric_bounds().unwrap(); + found = Some(((b.width() * 1e6).round() / 1e6, (b.height() * 1e6).round() / 1e6, n.children().map_or(0, |c| c.len()))); + } + }); + found + } + + fn open_from_menu(app: &mut VectorcraftApp) { + let entry = crate::menus::menu_entries(app).into_iter().find(|e| e.label == "Create Object Mosaic…").expect("menu item"); + let (cmd, params) = crate::menus::click_target(&entry.label, entry.command.as_deref().unwrap(), &entry.params); + crate::menus::invoke(app, &cmd, params); + } + + /// The menu item opens this dialog, not the generic one, on the image's size, with every documented row; OK + /// makes the mosaic as one undo step. + #[test] + fn the_menu_item_opens_the_dialog_with_its_rows() { + let mut app = app_with_image(); + open_from_menu(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog"); + assert_eq!(d.kind, KIND); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.f64("columns", 0.0), d.f64("rows", 0.0)), (100.0, 50.0, 10.0, 10.0)); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + for want in [ + "Create Object Mosaic", + "Current Size:", + "New Size:", + "Tile Spacing:", + "Number of Tiles:", + "Constrain Ratio:", + "Constrain Width and Height Proportions", + "Result:", + "Color", + "Grayscale", + "Resize Using Percentages", + "Delete Raster", + "Use Ratio", + "100 pt", + "50 pt", + ] { + assert!(texts.iter().any(|t| t == want), "{want:?} in {texts:?}"); + } + let undo = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 100))); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + } + + /// An image narrower than 0.1 pt opens with a new width of 0.1 pt, which OK makes. + #[test] + fn a_tiny_image_opens_with_a_size_the_command_takes() { + let mut app = app_with_image(); + app.run("object.scale", json!({"sx": 0.05, "sy": 100})).unwrap(); + open(&mut app, &json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("width", 0.0), 0.1); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| m.0), Some(0.1)); + } + + /// With no image selected the dialog does not open and the error says why. + #[test] + fn without_an_image_nothing_opens() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + let e = open(&mut app, &json!({})).unwrap_err(); + assert!(app.ui.dialog.is_none()); + assert!(e.contains("select an image"), "{e}"); + } + + /// Constrain Ratio keeps the new size in the image's proportions from the side it names; Resize Using + /// Percentages shows the same size as percentages; Use Ratio makes the tiles square from the kept side's count. + #[test] + fn constrain_ratio_percentages_and_use_ratio_set_the_fields() { + let mut app = app_with_image(); + open(&mut app, &json!({"columns": 10, "rows": 10})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lock".into(), json!(true)); + d.fields.insert("width".into(), json!(300)); + frame(&mut app, &ctx); + let mut d = app.ui.dialog.take().unwrap(); + assert_eq!(d.f64("height", 0.0), 150.0, "height follows the width"); + // Percentages: 300 × 150 pt of a 100 × 50 pt image is 300%. + switch_percentages(&mut d, true); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (300.0, 300.0)); + // Use Ratio: 10 columns across 300 pt are 30 pt tiles, so 5 rows down 150 pt. + use_ratio(&app, &mut d); + assert_eq!((count(&d, "columns"), count(&d, "rows")), (10, 5)); + // Kept by height: 4 rows of 37.5 pt over 300 pt are 8 columns. + d.fields.insert("constrain".into(), json!("height")); + d.fields.insert("rows".into(), json!(4)); + use_ratio(&app, &mut d); + assert_eq!((count(&d, "columns"), count(&d, "rows")), (8, 4)); + switch_percentages(&mut d, false); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (300.0, 150.0)); + d.fields.insert("gray".into(), json!(true)); + app.ui.dialog = Some(d); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app), Some((300.0, 150.0, 32))); + } + + /// With Constrain Ratio on, a kept width of 0.1 pt over a 100 × 50 pt image sets a height of + /// 0.05 pt, under the command's minimum: OK makes the 0.2 × 0.1 pt mosaic the command grows it to. + #[test] + fn a_constrained_size_under_the_minimum_grows_in_proportion() { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lock".into(), json!(true)); + d.fields.insert("width".into(), json!(0.1)); + frame(&mut app, &ctx); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("height", 0.0), 0.05, "height follows the width"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((0.2, 0.1))); + } + + /// A caller's params open the dialog with their values, and OK makes the mosaic they ask for. + #[test] + fn a_callers_params_open_the_dialog_with_their_values() { + let mut app = app_with_image(); + let params = json!({"columns": 4, "rows": 2, "width": 200, "percentages": true, "constrain": "width", "gray": true}); + app.run("ui.paramDialog", json!({"command": COMMAND, "label": "Create Object Mosaic", "params": params})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.kind, KIND); + assert_eq!( + (d.f64("width", 0.0), d.bool("percentages"), d.bool("lock"), d.str("constrain"), d.bool("gray")), + (200.0, true, true, "width".into(), true) + ); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app), Some((200.0, 100.0, 8))); + // Use Ratio given applies to the counts shown: 10 columns over 100 × 50 pt are 5 rows. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + let params = json!({"columns": 10, "rows": 3, "useRatio": true}); + app.run("ui.paramDialog", json!({"command": COMMAND, "params": params})).unwrap(); + assert_eq!(count(app.ui.dialog.as_ref().unwrap(), "rows"), 5); + // A side Use Ratio names is the side the dialog keeps: 4 rows over 100 × 50 pt are 8 columns. + let params = json!({"columns": 3, "rows": 4, "useRatio": "height"}); + app.run("ui.paramDialog", json!({"command": COMMAND, "params": params})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((count(d, "columns"), count(d, "rows"), d.str("constrain"), d.bool("lock")), (8, 4, "height".into(), false)); + app.ui.dialog = None; + // Params the command refuses open nothing and say why. + for (bad, key) in [(json!({"width": "abc"}), "width"), (json!({"constrain": "both"}), "constrain"), (json!({"widht": 200}), "widht")] { + let e = app.run("ui.paramDialog", json!({"command": COMMAND, "params": bad})).unwrap_err(); + assert!(app.ui.dialog.is_none(), "{e}"); + assert!(e.contains(key), "{e}"); + } + } + + /// `ui.dialog.set` of Resize Using Percentages shows the new size the other way, as the checkbox + /// does, so OK makes the same mosaic. Values the command refuses, set that way, are refused on OK + /// and make no mosaic. + #[test] + fn setting_fields_from_outside_keeps_the_size_or_is_refused() { + let mut app = app_with_image(); + open(&mut app, &json!({"width": 200, "height": 100})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (200.0, 200.0, true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((200.0, 100.0))); + app.run("edit.undo", json!({})).unwrap(); + // 0.1 × 0.1 pt of a 1000 × 500 pt image are 0.01% × 0.02%, under the command's 0.1%: the + // points stay, with the limit shown, and OK makes that size. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + app.run("object.scale", json!({"sx": 1000, "sy": 1000})).unwrap(); + open(&mut app, &json!({"width": 0.1, "height": 0.1})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (0.1, 0.1, false)); + assert!(d.str(form::REFUSED).contains("`width` must be between 0.1"), "{}", d.str(form::REFUSED)); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + assert!(texts.iter().any(|t| t.contains("must be between")), "the limit is shown: {texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((0.1, 0.1))); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + for (field, value) in [("percentages", json!("yes")), ("width", json!("abc")), ("gray", json!(1))] { + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), field.into(), value); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains(field), "{field}: {e}"); + assert_eq!(mosaic(&app), None, "{field}"); + } + // With Constrain Ratio on, a value the command refuses, set on the side it sets, is refused + // too, also after a frame. + for value in [json!("abc"), json!(0)] { + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "height".into(), value.clone()); + frame(&mut app, &ctx); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{value}: {e}"); + assert_eq!(mosaic(&app), None, "{value}"); + } + // Once that side holds a size the command takes, Constrain Ratio sets it again. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for (field, value) in [("height", json!(0)), ("lock", json!(false)), ("height", json!(80)), ("lock", json!(true))] { + crate::dialogs::set_field(d, field.into(), value); + } + frame(&mut app, &ctx); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("height", 0.0), 50.0); + // A refused height stays while a refused width is set and then corrected. + let d = app.ui.dialog.as_mut().unwrap(); + for (field, value) in [("height", json!(0)), ("width", json!(0)), ("width", json!(100))] { + crate::dialogs::set_field(d, field.into(), value); + } + frame(&mut app, &ctx); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{e}"); + assert_eq!(mosaic(&app), None); + } + + /// A width `ui.dialog.set` gave that is not a number stays when Resize Using Percentages is set, + /// with the mode unchanged and the reason shown, and OK refuses it. + #[test] + fn a_size_that_is_not_a_number_stays_when_percentages_switch() { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!("abc")); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.str("width"), d.bool("percentages")), ("abc".into(), false)); + assert!(d.str(form::REFUSED).contains("`width` must be a number"), "{}", d.str(form::REFUSED)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("width"), "{e}"); + assert_eq!(mosaic(&app), None); + } + + /// A size `ui.dialog.set` gave that the command refuses stays when Resize Using Percentages + /// switches, even when it is in range the other way (0.05 pt of a 10 pt wide image is 0.5%, and + /// 0.05% of a 1,000 pt wide image is 0.5 pt), with the mode unchanged and the reason shown, and + /// OK refuses it. + #[test] + fn a_size_out_of_range_stays_when_percentages_switch() { + for (scale, given, on) in [(10, json!({}), true), (1000, json!({"percentages": true}), false)] { + let mut app = app_with_image(); + app.run("object.scale", json!({"sx": scale, "sy": scale})).unwrap(); + open(&mut app, &given).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!(0.05)); + crate::dialogs::set_field(d, "percentages".into(), json!(on)); + assert_eq!((d.f64("width", 0.0), d.bool("percentages")), (0.05, !on), "{given}"); + assert!(d.str(form::REFUSED).contains("`width` must be between 0.1"), "{given}: {}", d.str(form::REFUSED)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("width"), "{given}: {e}"); + assert_eq!(mosaic(&app), None, "{given}"); + } + } + + /// The image scaled from 100 × 50 pt to 200 × 100 pt while the dialog is open: Current Size shows + /// the new size, and Resize Using Percentages, by `ui.dialog.set` or by its checkbox, converts + /// New Size against it, so OK makes the size shown. With no image selected, switching is refused. + #[test] + fn percentages_convert_against_the_image_scaled_while_the_dialog_is_open() { + let set = |app: &mut VectorcraftApp, field: &str, value: Value| { + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": field, "value": value})); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &egui::Context::default(), &req) else { + panic!("expected an immediate reply") + }; + r + }; + let mut app = app_with_image(); + open(&mut app, &json!({"width": 200, "height": 100})).unwrap(); + app.run("object.scale", json!({"sx": 200, "sy": 200})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + assert!(texts.iter().any(|t| t == "200 pt"), "Current Size shows the scaled image: {texts:?}"); + let r = set(&mut app, "percentages", json!(true)); + assert_eq!(r["ok"], json!(true), "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (100.0, 100.0, true)); + app.run("object.scale", json!({"sx": 50, "sy": 50})).unwrap(); + // The checkbox, after the image went back to 100 × 50 pt: 100% of it is 100 × 50 pt. + let size = image_size(&app); + let d = app.ui.dialog.as_mut().unwrap(); + read_image(size, d); + switch_percentages(d, false); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (100.0, 50.0)); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + app.run("object.scale", json!({"sx": 200, "sy": 200})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((200.0, 100.0)), "100% of the image as it is on OK"); + app.run("edit.undo", json!({})).unwrap(); + // No image selected: the mode and sizes stay and the dialog asks for an image. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + set(&mut app, "percentages", json!(true)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.bool("percentages")), (200.0, false)); + assert_eq!(d.str(form::REFUSED), NO_IMAGE_WHY); + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + set(&mut app, "percentages", json!(true)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.bool("percentages"), d.str(form::REFUSED)), (100.0, true, String::new())); + } + + /// A Constrain Ratio side other than width or height, or a Constrain Ratio that is not true or + /// false, set by `ui.dialog.set`, is refused on OK and makes no mosaic. + #[test] + fn a_constrain_ratio_value_the_command_refuses_is_refused() { + for (field, value, also) in [("constrain", json!("both"), Some(("lock", json!(true)))), ("lock", json!("yes"), None)] { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + if let Some((k, v)) = also { + crate::dialogs::set_field(d, k.into(), v); + } + crate::dialogs::set_field(d, field.into(), value.clone()); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains(field), "{value}: {e}"); + assert_eq!(mosaic(&app), None, "{value}"); + } + } + + /// When the command refuses the dialog's fields, OK leaves the dialog open with them, so they can + /// be corrected; OK then makes the mosaic and closes it. + #[test] + fn a_refused_field_keeps_the_dialog_open() { + let mut app = app_with_image(); + open(&mut app, &json!({"width": 80})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "gray".into(), json!(1)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("gray"), "{e}"); + assert_eq!(mosaic(&app), None); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + assert_eq!((d.f64("width", 0.0), d.fields.get("gray")), (80.0, Some(&json!(1)))); + crate::dialogs::set_field(d, "gray".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(mosaic(&app).map(|m| m.0), Some(80.0)); + } + + /// True or false set after a Resize Using Percentages value the command refuses replaces it: the + /// same mode as before keeps the sizes, and the other mode shows them the other way. Null is + /// false, as the command reads it. OK then makes the mosaic. + #[test] + fn true_or_false_replaces_a_refused_percentages_value() { + let pct = json!({"percentages": true, "width": 50, "height": 50}); + for (given, sets, size) in [ + (json!({}), vec![json!("yes"), json!(false)], (100.0, 50.0)), + (pct.clone(), vec![json!("yes"), json!(false)], (50.0, 25.0)), + (pct.clone(), vec![Value::Null], (50.0, 25.0)), + (pct, vec![json!("yes"), Value::Null], (50.0, 25.0)), + ] { + let mut app = app_with_image(); + open(&mut app, &given).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for value in sets { + crate::dialogs::set_field(d, "percentages".into(), value); + } + assert_eq!(d.fields.get("percentages"), Some(&json!(false)), "{given}"); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), size, "{given}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some(size), "{given}"); + } + } + + /// With Constrain Ratio on, a refused height `ui.dialog.set` gave is refused on OK even when it + /// equals the size Constrain Ratio works out from the width (0.05 pt from 0.1 pt over 100 × 50 pt). + #[test] + fn a_refused_height_equal_to_the_constrained_size_is_refused() { + let mut app = app_with_image(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!(0.1)); + crate::dialogs::set_field(d, "height".into(), json!(0.05)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{e}"); + assert_eq!(mosaic(&app), None); + } + + /// A percentage typed in New Size above 1,000,000 is kept at 1,000,000, the most the command + /// takes, so Enter makes the mosaic: 1,000,000% of the 100 pt width is 1,000,000 pt. + #[test] + fn a_typed_percentage_stays_within_what_the_command_takes() { + let mut app = app_with_image(); + open(&mut app, &json!({"percentages": true})).unwrap(); + let ctx = context(); + let run = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|s| { + if let egui::epaint::Shape::Text(t) = &s.shape { + Some((t.galley.text().to_string(), t.visual_bounding_rect().center())) + } else { + None + } + }) + .collect::>() + }; + run(&mut app, vec![]); + let texts = run(&mut app, vec![]); + // New Size's Width field comes right after the row's Width caption. + let row = texts.iter().position(|(t, _)| t == "New Size:").expect("the New Size row"); + let width = texts[row..].iter().position(|(t, _)| t == "Width:").and_then(|i| texts.get(row + i + 1)); + assert_eq!(width.map(|(t, _)| t.as_str()), Some("100%"), "{texts:?}"); + let at = width.map(|(_, p)| *p).unwrap(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); + run(&mut app, vec![press(false)]); + run(&mut app, vec![]); + run(&mut app, vec![egui::Event::Text("2000000".into())]); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + run(&mut app, vec![enter]); + assert!(app.ui.dialog.is_none(), "Enter makes the mosaic: {:?}", app.ui.dialog.as_ref().map(|d| d.str(form::REFUSED))); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((1e6, 50.0))); + } + + /// The id of the image in the document. + fn image_id(app: &VectorcraftApp) -> u64 { + let mut id = None; + app.session.active().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + id = Some(n.id.0); + } + }); + id.unwrap() + } + + /// #1000: the count the dialog holds reaches the command, so a count of 3.0 makes three columns. + #[test] + fn a_count_reaches_the_command() { + let mut app = app_with_image(); + open_from_menu(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("columns".into(), json!(3.0)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| m.2), Some(30)); + } +} diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 25d17d3902..3e69af017c 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -173,10 +173,10 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { Ok(r) } -/// Did a save whose applied result is `r` write the document (no error, and no question asked -/// before writing)? +/// Did a save whose applied result is `r` write the document (no error, no question asked before +/// writing, and not canceled by Cancel Save)? fn saved(r: &Result) -> bool { - r.as_ref().is_ok_and(|r| r.get("pending").is_none()) + r.as_ref().is_ok_and(|r| r.get("pending").is_none() && r.get("cancelled").and_then(Value::as_bool) != Some(true)) } /// Report the package `r` (`file.package`'s reply): the status bar, the web's download, and the diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index dd8db94418..de04998800 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -96,6 +96,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields.insert("printer".into(), json!(default)); fields.insert("toFile".into(), json!(!printers["service"].as_bool().unwrap_or(false))); fields.insert("__printers".into(), printers); + app.ui.print_direct_pdf = false; fields.insert("__section".into(), json!(SECTIONS[0])); fields.insert("__sheet".into(), json!(0)); // The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ). @@ -217,7 +218,16 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { app.ui.dialog = None; return Ok(json!({ "settings": settings })); } - let r = crate::print::run(app, &json!({ "settings": settings, "printer": d.str("printer"), "toFile": d.bool("toFile") }))?; + let direct_pdf = app.ui.print_direct_pdf; + let r = crate::print::run( + app, + &json!({ + "settings": settings, + "printer": d.str("printer"), + "toFile": d.bool("toFile"), + "directPdf": direct_pdf, + }), + )?; app.ui.dialog = None; Ok(r) } @@ -372,6 +382,11 @@ fn printer_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { app.status(e); } }); + if service && cfg!(windows) { + let to_file = d.bool("toFile"); + ui.add_enabled(!to_file, egui::Checkbox::new(&mut app.ui.print_direct_pdf, "Send PDF directly (bypass driver)")); + note(ui, "Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size."); + } } /// `print.preview` of `settings` (an error when they can't print), cached until they or the diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index cfa699b7b9..b3cb557b61 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -3600,7 +3600,7 @@ mod tests { vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false } } - /// With art, the preview rewrites the group being edited, its other swatch included; Save + /// With art, the preview rewrites the group being edited and keeps its other swatch; Save /// Changes is still refused, as the group is without the preview, and Cancel leaves it as it was. #[test] fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused_while_previewing() { @@ -3623,8 +3623,9 @@ mod tests { d.fields.insert("rows".into(), Value::Array(rs)); frame(&mut app, &ctx, 0.1, vec![], 0); assert!(app.session.in_interaction(), "the art previews"); - let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.len()); - assert_eq!(previewed, Some(2), "the preview's rewrite of the group leaves out its other swatch"); + let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.clone()); + assert_eq!(previewed.as_ref().map(Vec::len), Some(3), "the preview's rewrite of the group keeps its other swatch"); + assert_eq!(previewed.and_then(|s| s.last().cloned()), Some(fade_swatch()), "with its paint"); let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); crate::dialogs::cancel(&mut app); diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 6ff967f95a..7ad629afb8 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -244,29 +244,41 @@ pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result Result { - preview_folder_in(&std::env::temp_dir(), PREVIEW_KEEP) + temp_folder_under(ROOT) } -/// The name of a folder that a preview made in the temporary folder, beside a `VectorCraft Save -/// for Web` it couldn't use, before the process id and the count. +/// A new folder for a browser preview in the system's temporary folder, under the folder named +/// `root` ([`preview_folder_under`]). #[cfg(not(target_arch = "wasm32"))] -const BESIDE: &str = "VectorCraft Save for Web "; +pub(super) fn temp_folder_under(root: &str) -> Result { + preview_folder_under(&std::env::temp_dir(), root, PREVIEW_KEEP) +} -/// A new folder for a browser preview in the temporary folder `tmp`: inside `VectorCraft Save for -/// Web` ([`preview_folder`]), or, when that folder can't be used, directly in `tmp`, named -/// [`BESIDE`] followed by the process id and a count. The log says why the shared folder wasn't -/// used. Each preview first removes the folders of that name in `tmp` last changed `keep` or longer -/// ago ([`remove_old`]). -#[cfg(not(target_arch = "wasm32"))] +/// A new folder for a Save for Web browser preview in the temporary folder `tmp` +/// ([`preview_folder_under`] with `VectorCraft Save for Web`). +#[cfg(all(test, not(target_arch = "wasm32")))] pub(super) fn preview_folder_in(tmp: &std::path::Path, keep: std::time::Duration) -> Result { - remove_old(tmp, BESIDE, keep); - preview_folder(&tmp.join("VectorCraft Save for Web"), keep).or_else(|e| { - log::warn!("vectorcraft: Preview in Browser can't use {e}, so the preview goes to a new folder of its own"); - new_folder(tmp, BESIDE) + preview_folder_under(tmp, ROOT, keep) +} + +/// A new folder for a browser preview in the temporary folder `tmp`: inside the folder named `root` +/// ([`preview_folder`]), or, when that folder can't be used, directly in `tmp`, named `root`, a +/// space, the process id and a count. The log says why the shared folder wasn't used. Each preview +/// first removes the folders of that name in `tmp` last changed `keep` or longer ago +/// ([`remove_old`]). Previews under one `root` never remove the folders of another. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn preview_folder_under(tmp: &std::path::Path, root: &str, keep: std::time::Duration) -> Result { + let beside = format!("{root} "); + remove_old(tmp, &beside, keep); + preview_folder(&tmp.join(root), keep).or_else(|e| { + log::warn!("vectorcraft: a browser preview can't use {e}, so the preview goes to a new folder of its own"); + new_folder(tmp, &beside) }) } @@ -388,7 +400,7 @@ fn is_preview_name(name: &std::ffi::OsStr, prefix: &str) -> bool { } #[cfg(target_arch = "wasm32")] -fn temp_folder() -> Result { +pub(super) fn temp_folder_under(_: &str) -> Result { Err("no file system here".into()) } @@ -632,9 +644,9 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set ui.add_space(6.0); let mut browser = false; // Preview in Browser goes on a row of its own when the panes are too narrow for it beside the - // two lists (its width as `widgets::secondary_button` draws it). - let label = tl!("Preview in Browser"); - let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0); + // two lists. + let label = "Preview in Browser"; + let button_w = widgets::button_width(ui, label); let mut beside = false; let mut button = |ui: &mut egui::Ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index edfb66e7f4..85ff601db0 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -552,10 +552,12 @@ fn apply_preset(app: &mut VectorcraftApp, d: &mut Dialog, name: &str) { const OPTION_FLAGS: [&str; 2] = ["__requireOpenPassword", "__restrictPermissions"]; /// Replace every option with `settings` (from [`settings_fields`]), the password checkboxes -/// included. The preset, the artboard choice, the path and the other UI-only fields (the section, -/// the Save Preset name) stay. +/// included, and let the bleed link follow the new values. The preset, the artboard choice, the +/// path and the other UI-only fields (the section, the Save Preset name) stay. fn replace_settings(d: &mut Dialog, settings: Map) { - d.fields.retain(|k, _| matches!(k.as_str(), "preset" | "range" | "path") || (k.starts_with("__") && !OPTION_FLAGS.contains(&k.as_str()))); + d.fields.retain(|k, _| { + matches!(k.as_str(), "preset" | "range" | "path") || (k.starts_with("__") && !OPTION_FLAGS.contains(&k.as_str()) && k != BLEED_LINKED) + }); d.fields.extend(settings); } @@ -687,25 +689,106 @@ pub(super) fn marks_and_bleeds(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut flag(ui, d, "bleed.useDocument", tl!("Use document bleed settings"), true); // With the document's bleed the fields show it (Document Setup's `[top, bottom, left, right]`). let document = (get(d, "bleed.useDocument").as_bool() == Some(true)).then(|| app.session.active().map_or([0.0; 4], |s| s.doc.setup.bleed)); - egui::Grid::new("pdf-bleed").num_columns(4).spacing([10.0, 6.0]).show(ui, |ui| { - for pair in [ - [(0, "bleed.top", tl!("Top:")), (1, "bleed.bottom", tl!("Bottom:"))], - [(2, "bleed.left", tl!("Left:")), (3, "bleed.right", tl!("Right:"))], - ] { - for (i, p, label) in pair { - ui.label(label); - match document { - Some(b) => { - ui.add_enabled_ui(false, |ui| widgets::num_field(ui, p, b.get(i).copied(), unit, 80.0)); + // Save PDF and the PDF preset editor link the four sides; Print's Marks and Bleed doesn't. + let pdf = d.kind == KIND || d.kind == PRESET_KIND; + ui.horizontal(|ui| { + egui::Grid::new("pdf-bleed").num_columns(4).spacing([10.0, 6.0]).show(ui, |ui| { + for pair in [ + [(0, "bleed.top", tl!("Top:")), (1, "bleed.bottom", tl!("Bottom:"))], + [(2, "bleed.left", tl!("Left:")), (3, "bleed.right", tl!("Right:"))], + ] { + for (i, p, label) in pair { + ui.label(label); + match document { + Some(b) => { + ui.add_enabled_ui(false, |ui| widgets::num_field(ui, p, b.get(i).copied(), unit, 80.0)); + } + None if pdf => { + if let Some(x) = widgets::num_field(ui, p, get(d, p).as_f64(), unit, 80.0) { + edit_bleed(d, i, x); + } + } + None => length(ui, d, p, unit, true), } - None => length(ui, d, p, unit, true), } + ui.end_row(); + } + }); + if pdf { + let linked = bleed_linked(d); + let tip = if linked { tl!("Make the bleed values differ") } else { tl!("Make all bleed settings the same") }; + // With the document's bleed the link is grayed out and keeps its state for the custom values. + let clicked = ui + .add_enabled_ui(document.is_none(), |ui| widgets::icon_button(ui, if linked { "link" } else { "link-2-off" }, tip, linked, 24.0)) + .inner + .clicked(); + if clicked { + link_bleed(d, !linked); } - ui.end_row(); } }); } +/// The custom bleed's sides in Save PDF and the PDF preset editor, `[top, bottom, left, right]`. +const BLEED_SIDES: [&str; 4] = ["bleed.top", "bleed.bottom", "bleed.left", "bleed.right"]; +/// The field holding whether the link keeps the four custom bleed values the same. Without it, +/// the sides are linked when they are equal (a preset's, or ones `ui.dialog.set` set). +const BLEED_LINKED: &str = "__bleedLinked"; + +/// Whether the custom bleed's sides are linked. +fn bleed_linked(d: &Dialog) -> bool { + d.fields.get(BLEED_LINKED).and_then(Value::as_bool).unwrap_or_else(|| { + let top = get(d, BLEED_SIDES[0]).as_f64(); + BLEED_SIDES[1..].iter().all(|p| get(d, p).as_f64() == top) + }) +} + +/// Link (every side takes the top's value) or unlink (the sides keep their values) the bleed. +fn link_bleed(d: &mut Dialog, on: bool) { + d.fields.insert(BLEED_LINKED.into(), json!(on)); + if on { + let top = get(d, BLEED_SIDES[0]).as_f64().unwrap_or(0.0); + for p in &BLEED_SIDES[1..] { + set(d, p, json!(top)); + } + } +} + +/// Side `side` of the custom bleed was edited to `value`: linked, every side takes it. The link +/// keeps the state it had before the edit, so an unlinked edit that makes the sides equal leaves +/// it off. +fn edit_bleed(d: &mut Dialog, side: usize, value: f64) { + let linked = bleed_linked(d); + d.fields.insert(BLEED_LINKED.into(), json!(linked)); + if linked { + for p in BLEED_SIDES { + set(d, p, json!(value)); + } + } else if let Some(p) = BLEED_SIDES.get(side) { + set(d, p, json!(value)); + } +} + +/// `ui.dialog.set` set `field` of Save PDF or the PDF preset editor: `__bleedLinked` links or +/// unlinks the bleed as its button does, and must be true or false; every write of `bleed`, the +/// same values included, drops the link's state, so the link follows the values set. +pub(super) fn field_set(d: &mut Dialog, field: &str) -> Result<(), String> { + match field { + BLEED_LINKED => match d.fields.get(BLEED_LINKED).cloned() { + Some(Value::Bool(on)) => { + link_bleed(d, on); + Ok(()) + } + v => Err(format!("{BLEED_LINKED} must be true or false, not {}", v.unwrap_or(Value::Null))), + }, + "bleed" => { + d.fields.remove(BLEED_LINKED); + Ok(()) + } + _ => Ok(()), + } +} + /// A dropdown of names such as colour profiles or flattener presets (`names`, the first one /// standing for "" at `path`), showing the name at `path` (one that isn't among them too). The /// first `builtins` entries are ours (translated); the others (profiles, saved presets) are names. diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 6e02006cac..1f04c8c912 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -464,6 +464,201 @@ fn marks_and_bleeds_reach_the_pdf() { assert!(ellipse, "the non-printing layer is included"); } +/// The four custom bleed values, `[top, bottom, left, right]`. +fn bleed_of(d: &Dialog) -> [f64; 4] { + BLEED_SIDES.map(|p| get(d, p).as_f64().unwrap_or(f64::NAN)) +} + +/// Headless frames of the dialog layer with an accessibility tree, as a 1280 × 900 window. +struct LinkFrames(egui::Context); + +impl LinkFrames { + fn new() -> Self { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + theme::install_fonts(&ctx); + Self(ctx) + } + + fn run(&self, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let input = egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }; + let mut out = self.0.run_ui(input, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out + } + + /// The bleed link's button once the dialog has settled: its name, whether it shows pressed, + /// whether it is grayed out, and its center. + fn link(&self, app: &mut VectorcraftApp) -> (String, bool, bool, egui::Pos2) { + self.run(app, vec![]); + let out = self.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let names = ["Make the bleed values differ", "Make all bleed settings the same"]; + let mut found = nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button && n.label().is_some_and(|l| names.contains(&l))); + let (_, n) = found.next().expect("a bleed link button"); + assert!(found.next().is_none(), "one bleed link button"); + let b = n.bounds().expect("bounds"); + let pressed = n.toggled() == Some(egui::accesskit::Toggled::True) || n.is_selected() == Some(true); + let center = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + (n.label().unwrap_or_default().to_string(), pressed, n.is_disabled(), center) + } + + fn click(&self, app: &mut VectorcraftApp, at: egui::Pos2) { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + self.run(app, vec![egui::Event::PointerMoved(at), press(true)]); + self.run(app, vec![press(false)]); + } +} + +/// The link button beside the custom bleed values: the built-in presets' equal sides open linked, +/// an edit to one side sets all four while linked and only that one while unlinked, and linking +/// again gives every side the top's value. The link isn't an export option, and the linked values +/// reach the PDF's page boxes. +#[test] +fn the_bleed_link_keeps_the_four_sides_the_same() { + let (mut app, written, _) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/bleed.pdf"})).unwrap(); + set_field(&mut app, "__section", json!("Marks and Bleeds")); + let f = LinkFrames::new(); + let (name, pressed, disabled, at) = f.link(&mut app); + assert_eq!((name.as_str(), pressed, disabled), ("Make the bleed values differ", true, false), "equal sides open linked"); + edit_bleed(app.ui.dialog.as_mut().unwrap(), 2, 6.0); + assert_eq!(bleed_of(app.ui.dialog.as_ref().unwrap()), [6.0; 4], "linked: the left value sets all four"); + + f.click(&mut app, at); + let (name, pressed, ..) = f.link(&mut app); + assert_eq!((name.as_str(), pressed), ("Make all bleed settings the same", false), "the click unlinks"); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields.get(BLEED_LINKED), Some(&json!(false))); + edit_bleed(d, 1, 9.0); + edit_bleed(d, 3, 2.0); + assert_eq!(bleed_of(d), [6.0, 9.0, 6.0, 2.0], "unlinked: each side is its own"); + edit_bleed(d, 0, 4.0); + assert_eq!(bleed_of(d), [4.0, 9.0, 6.0, 2.0]); + + let (.., at) = f.link(&mut app); + f.click(&mut app, at); + let (name, pressed, ..) = f.link(&mut app); + assert_eq!((name.as_str(), pressed), ("Make the bleed values differ", true), "the click links again"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(bleed_of(d), [4.0; 4], "linking gives every side the top's value"); + let p = params(d); + assert_eq!(p["bleed"], json!({"useDocument": false, "top": 4.0, "bottom": 4.0, "left": 4.0, "right": 4.0})); + assert!(p.get(BLEED_LINKED).is_none() && preset_params(d).get(BLEED_LINKED).is_none(), "the link is the dialog's own"); + + super::super::confirm(&mut app).unwrap(); + let bytes = &written.borrow()[0].1; + let page = &vectorcraft_pdf::info(bytes, None).unwrap().pages[0]; + let bleed = page.boxes.iter().find(|(b, _)| *b == vectorcraft_pdf::CropTo::Bleed).expect("a bleed box").1; + let trim = page.boxes.iter().find(|(b, _)| *b == vectorcraft_pdf::CropTo::Trim).expect("a trim box").1; + assert_eq!((trim.x0 - bleed.x0, trim.y0 - bleed.y0, bleed.x1 - trim.x1, bleed.y1 - trim.y1), (4.0, 4.0, 4.0, 4.0)); +} + +/// A preset whose four bleed values differ opens unlinked; choosing a preset or Reset sets the link +/// from that preset's values rather than keeping the one shown before. +#[test] +fn presets_and_reset_set_the_bleed_link_from_their_values() { + let (mut app, _, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!bleed_linked(d), "unequal sides open unlinked"); + assert_eq!(bleed_of(d), [3.0, 5.0, 3.0, 3.0], "opening leaves the values as they are"); + + let mut d = d.clone(); + link_bleed(&mut d, true); + apply_preset(&mut app, &mut d, "Uneven"); + assert!(!bleed_linked(&d) && bleed_of(&d) == [3.0, 5.0, 3.0, 3.0], "choosing the preset takes its values and its link"); + apply_preset(&mut app, &mut d, pdf::DEFAULT_PRESET); + assert!(bleed_linked(&d), "the default preset's sides are equal"); + link_bleed(&mut d, false); + app.ui.dialog = Some(d); + app.run("ui.dialogReset", json!({})).unwrap(); + assert!(bleed_linked(app.ui.dialog.as_ref().unwrap()), "Reset sets the link from the preset's values"); + + // The preset editor has the same link. + open_preset(&mut app, &json!({"name": "Uneven"})).unwrap(); + set_field(&mut app, "__section", json!("Marks and Bleeds")); + let f = LinkFrames::new(); + let (name, pressed, disabled, at) = f.link(&mut app); + assert_eq!((name.as_str(), pressed, disabled), ("Make all bleed settings the same", false, false)); + f.click(&mut app, at); + assert_eq!(bleed_of(app.ui.dialog.as_ref().unwrap()), [3.0; 4]); +} + +/// With Use Document Bleed Settings on, the fields show the document's bleed and the link is +/// grayed out; the custom values and the link stay as they were for when it is turned off. +#[test] +fn the_document_bleed_grays_the_link_and_keeps_the_custom_values() { + let (mut app, _, _) = app(); + app.run("document.setup", json!({"bleed": 9})).unwrap(); + app.run("ui.savePdfDialog", json!({"bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + set_field(&mut app, "__section", json!("Marks and Bleeds")); + set_field(&mut app, "bleed.useDocument", json!(true)); + let f = LinkFrames::new(); + let (name, pressed, disabled, at) = f.link(&mut app); + assert_eq!((name.as_str(), pressed, disabled), ("Make all bleed settings the same", false, true)); + f.click(&mut app, at); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.fields.contains_key(BLEED_LINKED), "a grayed-out link does not change"); + assert_eq!(bleed_of(d), [3.0, 5.0, 3.0, 3.0]); + set_field(&mut app, "bleed.useDocument", json!(false)); + let (name, _, disabled, _) = f.link(&mut app); + assert_eq!((name.as_str(), disabled), ("Make all bleed settings the same", false)); +} + +/// `ui.dialog.set` can set the link (`__bleedLinked`) as its button does, refuses a value other +/// than true or false, and a new `bleed` lets the link follow its values. +#[test] +fn ui_dialog_set_links_the_bleed() { + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({"bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + let set = |app: &mut VectorcraftApp, field: &str, value: Value| { + let d = app.ui.dialog.as_mut().unwrap(); + assert!(super::super::accepts_field(d, field), "{field}"); + let old = d.fields.get(field).cloned(); + super::super::set_field(d, field.into(), value); + super::super::field_set(app, field, old.as_ref()) + }; + set(&mut app, BLEED_LINKED, json!(true)).unwrap(); + assert_eq!(bleed_of(app.ui.dialog.as_ref().unwrap()), [3.0; 4], "linking gives every side the top's value"); + for bad in [json!("yes"), json!(1), Value::Null] { + let e = set(&mut app, BLEED_LINKED, bad.clone()).unwrap_err(); + assert!(e.contains("__bleedLinked must be true or false"), "{bad}: {e}"); + } + set(&mut app, BLEED_LINKED, json!(false)).unwrap(); + set(&mut app, "bleed", json!({"top": 1, "bottom": 1, "left": 1, "right": 1})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.fields.contains_key(BLEED_LINKED) && bleed_linked(d), "equal values set are linked"); + set(&mut app, "bleed", json!({"top": 1, "bottom": 2, "left": 1, "right": 1})).unwrap(); + assert!(!bleed_linked(app.ui.dialog.as_ref().unwrap()), "unequal values set are unlinked"); + + // Writing the same `bleed` again also lets the link follow its values; a `__bleedLinked` set + // after it in the same request still decides. + set(&mut app, "bleed", json!({"top": 1, "bottom": 1, "left": 1, "right": 1})).unwrap(); + set(&mut app, BLEED_LINKED, json!(false)).unwrap(); + set(&mut app, "bleed", json!({"top": 1, "bottom": 1, "left": 1, "right": 1})).unwrap(); + assert!(bleed_linked(app.ui.dialog.as_ref().unwrap()), "the same equal values set again are linked"); + set(&mut app, BLEED_LINKED, json!(false)).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!bleed_linked(d) && bleed_of(d) == [1.0; 4], "a later __bleedLinked unlinks them"); +} + +/// An unlinked edit that makes the four sides equal leaves the link off, so the next edit +/// changes one side only. +#[test] +fn an_unlinked_edit_that_evens_the_sides_keeps_the_link_off() { + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({"bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert!(!bleed_linked(d)); + edit_bleed(d, 1, 3.0); + assert!(!bleed_linked(d), "the link stays off"); + edit_bleed(d, 2, 6.0); + assert_eq!(bleed_of(d), [3.0, 3.0, 6.0, 3.0], "the next edit changes one side"); +} + #[test] fn option_labels_read_well() { assert_eq!(option_label("compression.color.abovePpi"), "Compression › Color › Above Ppi"); diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index e6c9a6ee0a..3409a0b987 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -518,6 +518,10 @@ pub fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } if let Some(k) = app.ui.dialog.as_mut() { k.fields.insert("overrides".into(), crate::keymap::stored::to_value(&shortcut_editor::saved_overrides(km.overrides(), &ov))); + // VectorCraft's defaults have no hold shortcuts; Add to the Current Shortcuts keeps them. + if !current { + k.fields.insert("holds".into(), json!({})); + } k.fields.insert("set".into(), json!(set)); k.fields.insert("__message".into(), json!(tl!("Imported. Press OK to keep the imported set."))); } diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index 13586ae3e1..c185a3d5cb 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -1,16 +1,19 @@ //! SVG Options (Export As SVG, Save As / Save a Copy to .svg): profile, styling, fonts, images, //! object ids, decimals, encoding, minify, responsive, embedded fonts, artboards (export) or //! editing data (save), and a read-only view of the code. OK remembers the choices for next time and runs the export or save command with -//! them as `svg: {…}`. +//! them as `svg: {…}`. Show in Browser (`file.export.svg.browser`) writes the SVG the choices give +//! to a temporary folder and opens it in the default browser, leaving the dialog open. +use std::borrow::Cow; use std::sync::Arc; use serde_json::{Map, Value, json}; +use vectorcraft_engine::cmd::fileio; use super::DialogSpec; use crate::state::Dialog; use crate::theme::{self, Tokens}; -use crate::{VectorcraftApp, widgets}; +use crate::{VectorcraftApp, io, widgets}; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("SVG Options").into(), @@ -26,6 +29,12 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// `Dialog::kind` of this dialog. pub const KIND: &str = "svgOptions"; +/// The UI command of the dialog's Show in Browser button. +pub const BROWSER: &str = "file.export.svg.browser"; + +/// The folder in the system's temporary folder that Show in Browser's previews go to. +const PREVIEW_ROOT: &str = "VectorCraft SVG Preview"; + /// What OK does: Export As SVG, Save As or Save a Copy. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { @@ -196,8 +205,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } ui.add_space(10.0); let show = d.bool("showCode"); - if widgets::secondary_button(ui, if show { tl!("Hide Code") } else { tl!("Show Code") }).clicked() { - d.fields.insert("showCode".into(), json!(!show)); + let mut browser = false; + ui.horizontal(|ui| { + if widgets::secondary_button(ui, if show { tl!("Hide Code") } else { tl!("Show Code") }).clicked() { + d.fields.insert("showCode".into(), json!(!show)); + } + let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Show in Browser"))); + browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); + }); + if browser && let Err(e) = app.run(BROWSER, preview_params(d)) { + app.status(e); } if show { ui.add_space(6.0); @@ -269,6 +286,102 @@ fn artboards(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { }); } +/// The SVG options the dialog `d`'s OK writes with: [`options`], with hidden layers kept (not +/// displayed) when OK saves, as a save keeps them unless told otherwise. +fn written_options(d: &Dialog) -> Value { + let mut o = options(d); + if Mode::of(d) != Mode::Export + && let Some(m) = o.as_object_mut() + { + m.entry("hiddenLayers").or_insert(json!(true)); + } + o +} + +/// The params of [`BROWSER`] for the dialog `d`: the SVG options OK writes with +/// ([`written_options`]), and `exportSelection` when Export Selection opened it. +fn preview_params(d: &Dialog) -> Value { + super::export_as::exported(d, json!({ "svg": written_options(d) })) +} + +/// The SVG file that the SVG options `svg` write for one page of the document `st`, and the +/// document it is drawn from. With `selection` (Export Selection) the page is the selection alone, +/// cropped to it. Otherwise it is the first artboard the options choose, checked against the +/// document's artboards as OK checks them, or what the options write without artboards (also for +/// a document that has none). Linked scripts and images are checked against the read roots in +/// force first. +fn encode_page<'a>( + st: &'a vectorcraft_engine::DocState, + svg: &Value, + selection: bool, +) -> Result<(Cow<'a, vectorcraft_doc::Document>, fileio::Encoded), String> { + let mut opts = svg.clone(); + if let Some(o) = opts.as_object_mut() { + if selection { + // Export Selection writes one crop, without artboards to choose. + for k in fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]) { + o.remove(*k); + } + } else if st.doc.artboards.is_empty() { + for k in fileio::ARTBOARD_PARAMS { + o.remove(k); + } + } else { + let pick: fileio::ArtboardPick = serde_json::from_value(Value::Object(o.clone())).map_err(|e| e.to_string())?; + if let Some(first) = pick.resolve(st.doc.artboards.len())?.and_then(|v| v.first().copied()) { + for k in fileio::ARTBOARD_PARAMS { + o.remove(k); + } + o.insert("artboard".into(), json!(first)); + } + } + } + let params = json!({ "svg": opts }); + fileio::check_linked_scripts("document.export", "svg", st, ¶ms).map_err(|e| e.to_string())?; + let doc = if selection { + Cow::Owned(fileio::selection_doc(st, "document.exportSelection", false).map_err(|e| e.to_string())?.0) + } else { + Cow::Borrowed(&*st.doc) + }; + fileio::check_linked_images("document.export", "svg", st, &doc, ¶ms).map_err(|e| e.to_string())?; + let enc = fileio::encode_all(&doc, "svg", ¶ms).map_err(|e| e.to_string())?; + Ok((doc, enc)) +} + +/// `file.export.svg.browser {svg?, exportSelection?}` (SVG Options' Show in Browser): the SVG file +/// that the SVG options `svg` write for one page ([`encode_page`]), written with its linked images +/// to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder and opened in +/// the default browser (desktop) → `{path, warnings}`. Nothing is written to the chosen +/// destination, and the document, its path and the remembered choices are left as they were. +/// When the export has warnings, the status bar shows them as [`io::report_saved`] shows a save's +/// notes. Nothing opens when a check, the encoding or a write fails. +pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result { + if io::is_web(app) { + return Err("no file system here".into()); + } + app.refuse_automation(BROWSER)?; + let (selection, p) = io::take_selection(p)?; + let svg = p.get("svg").cloned().unwrap_or_else(|| json!({})); + let (path, warnings) = { + let st = app.session.active().ok_or("no document")?; + let stem = fileio::file_stem(&st.doc.title); + let (doc, enc) = encode_page(st, &svg, selection)?; + let dir = super::save_for_web::temp_folder_under(PREVIEW_ROOT)?; + let target = format!("{dir}/{}.svg", super::save_for_web::preview_name(&stem)); + let named = enc.named(&doc, &target); + for (p, bytes) in &named { + io::write_to(&mut app.services, p, bytes)?; + } + (named.first().map_or(target, |(p, _)| p.clone()), enc.notes()) + }; + app.open_url(&io::file_url(&path)); + let r = json!({ "path": path, "warnings": warnings }); + if !warnings.is_empty() { + io::report_saved(app, &path, &r); + } + Ok(r) +} + /// The SVG the current options write for the first chosen artboard, or under Export Selection for /// the selection alone, cropped to it (read-only, selectable), encoded again only when the /// options, the document or the selection change. @@ -276,19 +389,7 @@ fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { return }; let selection = d.bool(super::export_as::SELECTION_FIELD); - let mut opts = options(d); - if let Some(o) = opts.as_object_mut() { - if selection { - // Export Selection writes one crop, without artboards to choose. - for k in vectorcraft_engine::cmd::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]) { - o.remove(*k); - } - } else if let Some(r) = o.remove("range") { - // The first artboard of the range (or the first one). - let first = r.as_str().and_then(|r| r.split([',', '-', '\u{2013}']).next()).and_then(|n| n.trim().parse::().ok()); - o.insert("artboard".into(), json!(first.map_or(0, |n| n.saturating_sub(1)))); - } - } + let opts = written_options(d); // One cached text, replaced when the document, the options or the selection change. let key = egui::Id::unique("svg-code"); // The read roots in force and the document's folder decide whether the text may be shown. @@ -299,27 +400,15 @@ fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) { Some((_, c)) => c, None => { const MAX: usize = 200_000; - let params = json!({ "svg": opts }); - let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st, ¶ms).and_then(|()| { - let selected; - let doc = if selection { - selected = vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false)?.0; - &selected - } else { - &st.doc - }; - vectorcraft_engine::cmd::fileio::check_linked_images("document.export", "svg", st, doc, ¶ms)?; - vectorcraft_engine::cmd::fileio::encode_all(doc, "svg", ¶ms) - }); - let mut text = match encoded { + let mut text = match encode_page(st, &opts, selection) { // Shown as text whatever the file's encoding. - Ok(enc) => enc + Ok((_, enc)) => enc .files .into_iter() .next() .map(|(_, b)| vectorcraft_svg::text_of(&b).map_or_else(|_| String::from_utf8_lossy(&b).into_owned(), |t| t.into_owned())) .unwrap_or_default(), - Err(e) => e.to_string(), + Err(e) => e, }; if text.len() > MAX { let cut = (0..=MAX).rev().find(|i| text.is_char_boundary(*i)).unwrap_or(0); @@ -389,6 +478,153 @@ mod tests { String::from_utf8(w.borrow()[i].1.clone()).unwrap() } + type Opened = Rc>>; + + /// [`app`] whose browser records each URL it is asked to open. + fn browsing(picked: &str) -> (VectorcraftApp, Written, Opened) { + let (mut app, written) = app(picked); + let opened = Opened::default(); + let o = opened.clone(); + app.services.open_url = Some(Box::new(move |u: &str| o.borrow_mut().push(u.to_string()))); + (app, written, opened) + } + + /// Show in Browser for the open dialog's current choices, as its button runs it. + fn show_in_browser(app: &mut VectorcraftApp) -> Result { + let p = preview_params(app.ui.dialog.as_ref().expect("SVG Options open")); + app.run(BROWSER, p) + } + + /// Show in Browser writes the SVG of the dialog's current, unconfirmed choices for the first + /// artboard of the range to a new temporary folder and opens that file once. The dialog stays + /// open, nothing is remembered, and OK then writes the same SVG to the chosen file. + #[test] + fn show_in_browser_opens_what_ok_writes_without_confirming() { + let (mut app, written, opened) = browsing("/tmp/out.svg"); + app.run("file.export.svg", Value::Null).unwrap(); + frame(&mut app); + let f = &mut app.ui.dialog.as_mut().unwrap().fields; + f.insert("decimals".into(), json!(1)); + f.insert("allArtboards".into(), json!(false)); + f.insert("range".into(), json!("2")); + let remembered = app.ui.svg_options.clone(); + let r = show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + let path = r["path"].as_str().unwrap().to_string(); + assert!(path.contains("/VectorCraft SVG Preview/") && path.ends_with("/Untitled-1.svg"), "{path}"); + assert_eq!(*opened.borrow(), [io::file_url(&path)]); + assert_eq!(written.borrow().len(), 1); + assert_eq!(written.borrow()[0].0, path); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open"); + assert_eq!(app.ui.svg_options, remembered, "nothing is remembered"); + assert!(app.session.active().unwrap().path.is_none()); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(written.borrow()[1].0, "/tmp/out.svg"); + assert_eq!(text(&written, 0), text(&written, 1), "the preview is the file OK writes"); + assert_eq!(opened.borrow().len(), 1); + } + + /// A range the document has no artboard for is refused, as OK refuses it: nothing is written + /// or opened, and the dialog stays open. + #[test] + fn show_in_browser_refuses_a_range_the_document_lacks() { + let (mut app, written, opened) = browsing("/tmp/out.svg"); + app.run("file.export.svg", Value::Null).unwrap(); + let f = &mut app.ui.dialog.as_mut().unwrap().fields; + f.insert("allArtboards".into(), json!(false)); + f.insert("range".into(), json!("5")); + assert!(show_in_browser(&mut app).is_err()); + assert!(written.borrow().is_empty() && opened.borrow().is_empty()); + assert!(app.ui.dialog.is_some()); + } + + /// Under Export Selection the preview is the selection alone, cropped to it, as OK writes it. + #[test] + fn show_in_browser_under_export_selection_shows_the_selection() { + let (mut app, written, opened) = browsing("/tmp/selection.svg"); + app.run("shape.rectangle", json!({"x": 70, "y": 40, "width": 20, "height": 20})).unwrap(); + app.run("document.exportSelection", Value::Null).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool(super::super::export_as::SELECTION_FIELD)); + show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(written.borrow()[1].0, "/tmp/selection.svg"); + assert_eq!(text(&written, 0), text(&written, 1)); + assert_eq!(text(&written, 0).matches("