diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..2c7a07478b 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | diff --git a/Cargo.lock b/Cargo.lock index cec8e7aef7..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", @@ -6775,6 +6790,7 @@ dependencies = [ "craft-stream-codecs", "craft-xml", "crc32fast", + "encoding_rs", "flate2", "hayro-ccitt", "heic-rs", @@ -7108,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 2fb84ab127..ea37f12caf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -138,8 +138,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. +- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. @@ -152,7 +154,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. +- 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-web/src/api.rs b/apps/vectorcraft-web/src/api.rs index eddd04f1b7..1be921baf3 100644 --- a/apps/vectorcraft-web/src/api.rs +++ b/apps/vectorcraft-web/src/api.rs @@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin>> { }) } -async fn sleep(ms: i32) { +pub(crate) async fn sleep(ms: i32) { let promise = js_sys::Promise::new(&mut |resolve, _| { if let Some(window) = web_sys::window() { let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs new file mode 100644 index 0000000000..7583248701 --- /dev/null +++ b/apps/vectorcraft-web/src/demand.rs @@ -0,0 +1,139 @@ +//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most +//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after +//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures. + +/// The wait after a face's first failed fetch before it is fetched again (ms). +const RETRY_MS: i32 = 30_000; +/// Failed fetches of a face after which it is not fetched again this session. +pub(crate) const MAX_TRIES: u32 = 5; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum State { + Idle, + /// Being fetched, after `tries` failed fetches. + Loading { + tries: u32, + }, + Loaded, + /// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or + /// at once when the clock reads earlier than `failed_at`. + Failed { + tries: u32, + failed_at: f64, + retry_at: f64, + }, +} + +/// The fetch state of each face of a web font list, by index. +#[derive(Debug, Default)] +pub(crate) struct Demand { + states: Vec, +} + +impl Demand { + /// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not + /// loaded, not being fetched, and not waiting to be fetched again. They are marked as being + /// fetched. + pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec { + let mut out = Vec::new(); + for &i in wanted { + if self.states.len() <= i { + self.states.resize(i + 1, State::Idle); + } + let Some(state) = self.states.get_mut(i) else { continue }; + let tries = match *state { + State::Idle => Some(0), + State::Loading { .. } | State::Loaded => None, + State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries), + }; + if let Some(tries) = tries { + *state = State::Loading { tries }; + out.push(i); + } + } + out + } + + /// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`. + /// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it + /// loaded or has failed [`MAX_TRIES`] times. + pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option { + let state = self.states.get_mut(i)?; + let State::Loading { tries } = *state else { return None }; + if ok { + *state = State::Loaded; + return None; + } + let tries = tries + 1; + let wait = RETRY_MS << (tries - 1).min(4); + *state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) }; + (tries < MAX_TRIES).then_some(wait) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_face_is_fetched_once_and_kept() { + let mut d = Demand::default(); + assert_eq!(d.start(&[2], 0.0), [2]); + assert!(d.start(&[2], 1.0).is_empty(), "already being fetched"); + assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry"); + assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again"); + assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own"); + assert_eq!(d.finished(7, false, 4.0), None, "a face never started"); + } + + #[test] + fn a_failed_face_waits_longer_after_each_failure_and_then_stops() { + let mut d = Demand::default(); + let mut now = 0.0; + // The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first. + for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) { + assert_eq!(d.start(&[0], now), [0], "at {now}"); + assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}"); + assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}"); + now += f64::from(wait); + } + // The fifth fetch, and after it fails, none. + assert_eq!(d.start(&[0], now), [0]); + assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures"); + assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures"); + // A later success after failures keeps the face. + let mut d = Demand::default(); + d.start(&[1], 0.0); + assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS)); + assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]); + assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); + assert!(d.start(&[1], 1e12).is_empty()); + } + + /// While a face is fetched again after a failure, neither the interface asking for its script + /// again nor the retry timer starts a second fetch of it. + #[test] + fn a_face_being_fetched_again_is_not_fetched_twice_at_once() { + let mut d = Demand::default(); + d.start(&[0], 0.0); + assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS)); + let retry = f64::from(RETRY_MS); + assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice"); + assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again"); + assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer"); + assert_eq!(d.finished(0, true, retry + 2_000.0), None); + assert!(d.start(&[0], 1e12).is_empty(), "loaded"); + } + + /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the + /// retry back: the timer that asks for it has waited already. + #[test] + fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() { + let mut d = Demand::default(); + let failed_at = 1e12; + d.start(&[0], failed_at); + assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS)); + assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting"); + assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour"); + } +} diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index 2677c11edf..873474f6c3 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -1,17 +1,22 @@ //! Craft-fonts faces served beside the wasm (`fonts//…`, copied by //! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup` -//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks -//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped: -//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing. +//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and +//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the +//! interface's own text needs its script. The browser checks each file against its SHA-256 +//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With +//! `WEB_FONTS` empty (built without craft-fonts) these do nothing. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; +use vectorcraft_text::craft_fonts::demand_fonts; use vectorcraft_text::{FontDb, WEB_FONTS, WebFont}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use wasm_bindgen_futures::JsFuture; +use crate::demand::Demand; + /// Per startup face: the page shows its loading text meanwhile. const STARTUP_TIMEOUT_MS: i32 = 20_000; /// Per background face. @@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4; thread_local! { /// The background fetch runs once per page, though a graphics restart creates the app again. static BACKGROUND_STARTED: Cell = const { Cell::new(false) }; + /// The `demand` faces' fetches. + static DEMAND: RefCell = RefCell::new(Demand::default()); + /// The running app's context, asked for a frame when a `demand` face arrives (none before the + /// app starts: its first frame looks through the faces loaded by then). + static REPAINT: RefCell> = const { RefCell::new(None) }; +} + +/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or +/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those +/// characters with it from then on. Set as the interface's missing-glyph handler +/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name +/// before the app starts. +pub fn want_chars(chars: &[char]) { + let wanted = demand_fonts(WEB_FONTS, chars.iter().copied()); + if !wanted.is_empty() { + fetch_demand(&wanted); + } +} + +/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. +/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. +fn fetch_demand(wanted: &[usize]) { + for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) { + let Some(f) = WEB_FONTS.get(i) else { continue }; + wasm_bindgen_futures::spawn_local(async move { + let ok = load(f, BACKGROUND_TIMEOUT_MS).await; + let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms())); + if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { + ctx.request_repaint(); + } + if let Some(wait) = retry { + // A second longer, so a clock the browser coarsens still reads the wait as over. + crate::api::sleep(wait.saturating_add(1_000)).await; + fetch_demand(&[i]); + } + }); + } } /// Fetch and register the `startup` faces (one after the other). Returns how many loaded. pub async fn load_startup_fonts() -> usize { let mut loaded = 0; - for f in WEB_FONTS.iter().filter(|f| f.startup) { + for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) { if load(f, STARTUP_TIMEOUT_MS).await { loaded += 1; } @@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize { } /// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for -/// a frame after each so the font menus and the canvas pick it up. Only the first call does -/// anything. +/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches +/// anything; each call makes `ctx` the context a `demand` face asks for a frame. pub fn spawn_background_fonts(ctx: egui::Context) { + REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone())); if BACKGROUND_STARTED.with(|s| s.replace(true)) { return; } - let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect()); + let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect()); let next = Rc::new(Cell::new(0usize)); for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) { let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone()); diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index 457d8d4640..b71b51b566 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -21,6 +21,8 @@ #[cfg(target_arch = "wasm32")] mod api; +#[cfg(any(target_arch = "wasm32", test))] +mod demand; #[cfg(target_arch = "wasm32")] mod fonts; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 2de7f3b481..6d9e0cadd5 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -81,6 +81,11 @@ pub fn start() { return; }; detect_language(); + // The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the + // startup fonts, without holding up the start. Text in those scripts painted later (a saved + // interface language, another one chosen, a layer or file name) has its face fetched then. + vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars); + crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::>()); wasm_bindgen_futures::spawn_local(async move { // Before the first frame, which looks for copies a crash left behind. let locks = WebLocks::start(RECOVERY_PREFIX).await; 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/display_profile.rs b/apps/vectorcraft/src/display_profile.rs index 2be6e27aa5..ee35a407a7 100644 --- a/apps/vectorcraft/src/display_profile.rs +++ b/apps/vectorcraft/src/display_profile.rs @@ -10,7 +10,7 @@ //! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`). //! //! While the preference is on, a background thread reads the display every [`EVERY`] seconds, -//! and at once when the window moves to another display. +//! and at once when the window moves to another display or Edit › Refresh Monitor Profile asks. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -31,6 +31,8 @@ pub(crate) struct Reader { looked: Option, /// A reading is running. busy: Arc, + /// [`DisplayProfile::attach_reader`] was called. + attached: bool, } /// Clears [`Reader::busy`] when the reading thread ends, also by a panic. @@ -45,22 +47,22 @@ impl Drop for Done { impl Reader { /// Starts a reading when one is due and none is running. `now` is the frame's time in seconds. pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) { - if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { - return; + if !self.attached { + profile.attach_reader(); + self.attached = true; } - self.looked = Some(now); - let display = window.current_monitor().and_then(|m| m.name()); - if !due(self.last.as_ref(), now, display.as_deref()) { + let Some(display) = self.start(now, enabled, profile, || window.current_monitor().and_then(|m| m.name())) else { return; - } - self.last = Some((now, display.clone())); + }; profile.pending(); self.busy.store(true, Ordering::Release); let done = Done(self.busy.clone()); let (profile, ctx) = (profile.clone(), ctx.clone()); let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || { - let _done = done; - if profile.report(read(display)) { + let changed = profile.report(read(display)); + drop(done); + // A request made while this reading ran starts on the next frame. + if changed || profile.read_requested() { ctx.request_repaint(); } }); @@ -68,6 +70,32 @@ impl Reader { log::warn!("couldn't start reading the display profile: {e}"); } } + + /// The display to read at `now` when a reading is to start, looked up with `display`. A + /// request from Refresh Monitor Profile ([`DisplayProfile::request_read`]) starts one at once, + /// past [`EVERY`] and [`LOOK_EVERY`]; while a reading runs it waits, and a frame that finds the + /// preference off drops it. A request made with the preference on is kept when the preference + /// goes off and on again between two frames. + fn start(&mut self, now: f64, enabled: bool, profile: &DisplayProfile, display: impl FnOnce() -> Option) -> Option> { + if !enabled { + profile.take_request(); + return None; + } + if self.busy.load(Ordering::Acquire) { + return None; + } + let asked = profile.take_request(); + if !asked && self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { + return None; + } + self.looked = Some(now); + let display = display(); + if !asked && !due(self.last.as_ref(), now, display.as_deref()) { + return None; + } + self.last = Some((now, display.clone())); + Some(display) + } } /// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another @@ -570,6 +598,56 @@ mod tests { assert!(due(Some(&last), 50.0, Some("DP-1"))); } + fn attached() -> DisplayProfile { + let profile = DisplayProfile::default(); + profile.attach_reader(); + profile + } + + #[test] + fn a_requested_reading_starts_on_the_next_frame_past_both_intervals() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert_eq!(r.start(100.0, true, &profile, dp1), Some(Some("DP-1".into()))); + // Inside the display lookup interval and the reading interval: nothing starts. + assert_eq!(r.start(100.5, true, &profile, || panic!("not looked up")), None); + assert_eq!(r.start(102.0, true, &profile, dp1), None); + profile.request_read(true).unwrap(); + assert_eq!(r.start(102.1, true, &profile, dp1), Some(Some("DP-1".into()))); + assert!(!profile.read_requested(), "the request is taken"); + // The intervals run again from the requested reading. + assert_eq!(r.start(102.2, true, &profile, dp1), None); + assert_eq!(r.start(111.0, true, &profile, dp1), None); + assert_eq!(r.start(113.0, true, &profile, dp1), Some(Some("DP-1".into()))); + } + + #[test] + fn a_request_made_while_a_reading_runs_waits_for_it_to_end() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert!(r.start(0.0, true, &profile, dp1).is_some()); + r.busy.store(true, Ordering::Release); + profile.request_read(true).unwrap(); + assert_eq!(r.start(0.1, true, &profile, dp1), None); + assert_eq!(r.start(5.0, true, &profile, dp1), None); + assert!(profile.read_requested(), "kept while the reading runs"); + r.busy.store(false, Ordering::Release); + assert_eq!(r.start(5.1, true, &profile, dp1), Some(Some("DP-1".into()))); + assert!(!profile.read_requested()); + } + + #[test] + fn a_request_is_dropped_when_the_preference_goes_off() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert!(r.start(0.0, true, &profile, dp1).is_some()); + profile.request_read(true).unwrap(); + assert_eq!(r.start(0.1, false, &profile, dp1), None); + assert!(!profile.read_requested()); + assert_eq!(r.start(0.2, true, &profile, dp1), None, "no reading starts later for it"); + assert!(profile.request_read(false).is_err()); + } + #[test] fn wayland_sessions_are_told_apart_from_x11_by_the_environment() { let env = |pairs: &'static [(&'static str, &'static str)]| { diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 53e0484534..1ce124c1dd 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -96,7 +96,24 @@ fn dialog_for(d: D, request: &PickRequest) -> D { Some(folder) => d.folder(folder), None => d, }; - if pick.name.is_empty() { d } else { d.file_name(&pick.name) } + if pick.name.is_empty() { + return d; + } + // Windows' save dialog changes the extension when a different file type is chosen only when + // the suggested name has no explicit extension. rfd supplies the first filter's extension to + // that dialog, so leave the suffix to Windows for saves that offer several formats (#5451). + // A remaining dot in the stem would look like another explicit extension to Windows. + #[cfg(windows)] + if matches!(request, PickRequest::Save(_)) + && pick.filters.len() > 1 + && let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str()) + && pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext))) + && let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str()) + && !stem.contains('.') + { + return d.file_name(stem); + } + d.file_name(&pick.name) } #[cfg(test)] @@ -796,7 +813,7 @@ mod dialog_tests { /// The file types a dialog was given, by label. #[derive(Default)] - struct Filters(Vec<(String, Vec)>); + struct Filters(Vec<(String, Vec)>, Option); impl DialogSettings for Filters { fn parent(self, _window: &winit::window::Window) -> Self { @@ -812,7 +829,8 @@ mod dialog_tests { fn folder(self, _folder: &str) -> Self { self } - fn file_name(self, _name: &str) -> Self { + fn file_name(mut self, name: &str) -> Self { + self.1 = Some(name.to_string()); self } } @@ -869,4 +887,24 @@ mod dialog_tests { let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); } + + /// A format selected after the Windows Save As dialog opens can replace the suffix of the + /// suggested name. Single-format saves and open dialogs keep the supplied name verbatim. + #[cfg(windows)] + #[test] + fn save_dialog_with_several_formats_leaves_the_extension_to_windows() { + let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])]; + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster")); + assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft")); + + let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster")); + let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design")); + let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft")); + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft")); + } } 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/assets/icons/dc-circle-points.svg b/assets/icons/dc-circle-points.svg new file mode 100644 index 0000000000..46da3a3401 --- /dev/null +++ b/assets/icons/dc-circle-points.svg @@ -0,0 +1 @@ + diff --git a/crates/brush/src/calli.rs b/crates/brush/src/calli.rs index 888294356c..69a8463c92 100644 --- a/crates/brush/src/calli.rs +++ b/crates/brush/src/calli.rs @@ -9,7 +9,6 @@ //! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and //! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there. -use vectorcraft_color::Paint; use vectorcraft_doc::{Node, StrokeLayer}; use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2}; @@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option { Some(bp) } -pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec { +/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and +/// barrel rotation turn that spread in the path's local frame. Original path corners are included +/// in the samples so a turn is not rounded away by the pose sampling interval. +fn posed_bristle_track( + t: &Track, + d: f64, + trim0: f64, + trim1: f64, + size: f64, + stroke: &StrokeLayer, + varies: bool, +) -> Option<(BezPath, Vec<(f64, f64)>)> { + let l = t.len(); + let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l)); + if s1 - s0 < 1e-6 { + return None; + } + let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 }; + let mut positions: Vec = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect(); + positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1)); + positions.sort_by(f64::total_cmp); + positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut path = BezPath::new(); + // Distance along the posed strand -> fraction along the original, untrimmed path. + let mut source = Vec::with_capacity(positions.len()); + let mut previous: Option = None; + let mut distance = 0.0; + for (i, s) in positions.into_iter().enumerate() { + let pen = PenAt::of(stroke, s / l); + let pressure = pen.control(Variation::Pressure).unwrap_or(0.5); + let tilt = pen.control(Variation::Tilt).unwrap_or(0.5); + let bearing = pen.control(Variation::Bearing).unwrap_or(0.5); + let rotation = pen.control(Variation::Rotation).unwrap_or(0.5); + let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt); + let angle = std::f64::consts::TAU * (bearing + rotation - 1.0); + let p = t.map(s + spread * angle.sin(), spread * angle.cos()); + if i == 0 { + path.move_to(p) + } else { + path.line_to(p) + } + if let Some(previous) = previous { + distance += previous.distance(p); + } + source.push((distance, s / l)); + previous = Some(p); + } + Some((path, source)) +} + +fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 { + let next = source.partition_point(|(d, _)| *d < distance); + if next == 0 { + return source.first().map_or(0.0, |(_, f)| *f); + } + if next >= source.len() { + return source.last().map_or(1.0, |(_, f)| *f); + } + let (d0, f0) = source[next - 1]; + let (d1, f1) = source[next]; + if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) } +} + +pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec { let mut rng = Rng::new(seed_of(bp, name)); let size = b.size.max(0.1) * weight; let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize; @@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0; let ragged = b.length.clamp(25.0, 300.0) / 100.0; let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32; + let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some(); + let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6)); + let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points)); + let pose_varies = pressure_varies + || stroke.tilt.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.bearing.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.rotation.as_ref().is_some_and(|p| varies(&p.points)); let mut out = vec![]; for t in tracks(bp, tolerance(size)) { let l = t.len(); @@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let edge = 1.0 - lane.abs(); let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8; let (t0, t1) = (trim(&mut rng), trim(&mut rng)); - let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue }; + let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3)); + let sp = if posed { + posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies) + } else { + offset_track(&t, off, t0, t1).map(|path| (path, Vec::new())) + }; + let Some((sp, source)) = sp else { continue }; let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2); - let nib = Nib::new(0.0, 1.0, w); - let subs: Vec = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect(); + let subs: Vec = tracks(&sp, tolerance(w)) + .iter() + .flat_map(|tt| { + if posed { + sweep( + tt, + &|f| { + let original_fraction = source_fraction(&source, f * tt.len()); + let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5); + Nib::new(0.0, 1.0, w * (0.5 + pressure)) + }, + pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)), + ) + } else { + let nib = Nib::new(0.0, 1.0, w); + sweep(tt, &|_| nib, None) + } + }) + .collect(); if subs.is_empty() { continue; } - let mut n = filled(PathData::new(subs), paint); + let mut n = filled(PathData::new(subs), &stroke.paint); n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0); out.push(n); } diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index 00edeb3113..10dc66b587 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -97,6 +97,75 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { walk(n, mode, key); } +/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own +/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter. +const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474; + +/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its +/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's +/// [`crate::track::seed_of`]). +pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) { + let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT); + for n in copies { + let turn = rng.range(-amount, amount) as f32; + turn_hues(n, turn); + } +} + +/// `c` with its hue turned by `degrees`, worked out on its own components so nothing else about it +/// changes: RGB in HSB of its values, CMYK over C, M and Y with K kept (as +/// [`Color::complement_keep_model`] does), Lab by turning a and b. `None` for a color without a hue: +/// white, black and grays, in their own model (Gray, CMYK with no C, M or Y ink). +fn turned(c: &Color, degrees: f32) -> Option { + if !degrees.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() { + return None; + } + let turn = |v: [f32; 3]| { + let [h, s, b] = vectorcraft_color::rgb_to_hsb(v); + (s > 0.0).then(|| vectorcraft_color::hsb_to_rgb([(h + degrees).rem_euclid(360.0), s, b])) + }; + match *c { + Color::Rgb { r, g, b } => turn([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)), + Color::Cmyk { c, m, y, k } => turn([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)), + Color::Gray { .. } => None, + Color::Lab { l, a, b } => { + let (sin, cos) = f64::from(degrees).to_radians().sin_cos(); + let (a, b) = (f64::from(a), f64::from(b)); + Some(Color::lab(l, (a * cos - b * sin) as f32, (a * sin + b * cos) as f32)) + } + } +} + +fn turn_paint(p: &mut Paint, degrees: f32) { + if let Paint::Solid { color, .. } = p + && let Some(c) = turned(color, degrees) + { + *p = Paint::solid(c); + } +} + +/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A +/// mask's colors are its values, so they stay. +fn turn_hues(n: &mut Node, degrees: f32) { + for it in &mut n.appearance.items { + match it { + AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees), + AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees), + } + } + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + turn_paint(&mut r.style.fill, degrees); + turn_paint(&mut r.style.stroke, degrees); + } + } + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + turn_hues(Arc::make_mut(c), degrees); + } + } +} + /// Strip the brushes from every stroke under `n`, its masks' art included. fn strip_brushes(n: &mut Node) { for it in &mut n.appearance.items { diff --git a/crates/brush/src/defaults.rs b/crates/brush/src/defaults.rs index 8cf7467397..b99f36ecec 100644 --- a/crates/brush/src/defaults.rs +++ b/crates/brush/src/defaults.rs @@ -172,6 +172,7 @@ pub fn defaults() -> &'static [Brush] { rotation: (-180.0, 180.0), rotation_relative_to_path: false, colorization: Colorization::Tints, + hue_jitter: 0.0, modes: None, }), }, @@ -185,6 +186,7 @@ pub fn defaults() -> &'static [Brush] { rotation: (-35.0, 35.0), rotation_relative_to_path: true, colorization: Colorization::None, + hue_jitter: 0.0, modes: None, }), }, diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 7129279b31..c5354d75cd 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -298,6 +298,12 @@ pub struct Scatter { /// Rotation relative to the path direction (else to the page). pub rotation_relative_to_path: bool, pub colorization: Colorization, + /// Hue jitter in degrees, 0 to 180: each copy turns the hue of the solid colors it draws, after + /// the colorization, by its own amount between −`hue_jitter` and `hue_jitter`. The stroke's + /// path and the brush name fix the amounts, so a stroke draws the same colors every time. + /// 0 (brushes saved before there was hue jitter) leaves the colors as they are. + #[serde(skip_serializing_if = "is_zero")] + pub hue_jitter: f64, /// How size, spacing, scatter and rotation vary between their two values: Fixed takes the /// first, Random any value between them, Pressure the first at the lightest pen pressure and /// the second at the heaviest, Tilt the first with the pen lying flat and the second upright, @@ -318,6 +324,7 @@ impl Default for Scatter { rotation: (0.0, 0.0), rotation_relative_to_path: false, colorization: Colorization::None, + hue_jitter: 0.0, modes: None, } } @@ -326,6 +333,8 @@ impl Default for Scatter { impl Scatter { /// The ranges of size (%), spacing (%), scatter (%) and rotation (°). pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)]; + /// The range of [`Scatter::hue_jitter`] (°). + pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0); /// Size, spacing, scatter and rotation, each as its (first, second) values. pub fn values(&self) -> [(f64, f64); 4] { @@ -624,6 +633,10 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6 (within(a, range, fallback), within(b, range, fallback)) } +fn is_zero(v: &f64) -> bool { + *v == 0.0 +} + fn valid_tile_frame(frame: Rect) -> bool { [frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite) && frame.width().is_finite() @@ -714,6 +727,7 @@ impl Brush { s.spacing = within_pair(s.spacing, spacing, d.spacing.0); s.scatter = within_pair(s.scatter, scatter, 0.0); s.rotation = within_pair(s.rotation, rotation, 0.0); + s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0); s.colorization.sanitize(); } BrushKind::Art(a) => { @@ -1084,7 +1098,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok let w = if stroke.width > 0.0 { stroke.width } else { 1.0 }; let mut out = match &brush.kind { BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name), - BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name), + BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), BrushKind::Pattern(p) => warp::pattern(p, bp, w), @@ -1093,6 +1107,12 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok for n in &mut out { colorize(n, colorization, &stroke.paint); } + // One piece per copy, in the order the copies run along the path. + if let BrushKind::Scatter(s) = &brush.kind + && s.hue_jitter > 0.0 + { + colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name)); + } leave_out_brushed(doc, &mut out, &mut Known::new()); out } @@ -1245,6 +1265,14 @@ pub fn has_brush(n: &Node) -> bool { n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible)) } +/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes +/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so +/// the profile does not change what such a stroke draws. A stroke without a brush, or one that +/// names a brush `lib` lacks, draws a plain stroke, which follows the profile. +pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool { + stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name)) +} + /// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest /// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has /// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 437ec4028f..f4f2d1ae20 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -827,6 +827,86 @@ fn bristle_makes_translucent_strands() { assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}"); } +#[test] +fn bristle_pen_pressure_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |pressure| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let light = render(0.0); + let heavy = render(1.0); + assert_eq!(light.len(), heavy.len()); + assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8); +} + +#[test] +fn bristle_pen_pressure_is_sampled_along_the_stroke() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }; + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s); + let mut points = Vec::new(); + for n in &out { + all_points(n, &mut points); + } + let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + assert!(late > early * 1.4, "spread along stroke: {early} -> {late}"); +} + +#[test] +fn trimmed_bristle_strands_read_pressure_where_they_begin() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) }; + let render = |points| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s) + }; + let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]); + let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]); + assert_eq!(ramp.len(), neutral.len()); + let start = |n: &Node| { + let anchors = &n.path_data().unwrap().subpaths[0].anchors; + let first = anchors[0].p; + let opposite = anchors[anchors.len() - 16].p; + (first.x, (first.y - opposite.y).abs()) + }; + let mut checked = false; + for (ramp, neutral) in ramp.iter().zip(&neutral) { + let (x, width) = start(ramp); + if x < 12.0 { + continue; + } + let (_, neutral_width) = start(neutral); + let expected = 0.5 + x / 80.0; + assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); + checked = true; + } + assert!(checked, "at least one strand begins past the pressure ramp's first eighth"); +} + +#[test] +fn bristle_pen_orientation_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |tilt, bearing, rotation| { + let flat = |x| vec![(0.0, x), (1.0, x)]; + let s = StrokeLayer { + tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }), + bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }), + rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }), + ..stroke(1.0) + }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let neutral = bounds(&render(0.5, 0.0, 0.0)).height(); + let flat = bounds(&render(1.0, 0.0, 0.0)).height(); + let upright = bounds(&render(0.0, 0.0, 0.0)).height(); + let bearing = bounds(&render(0.5, 90.0, 0.0)).height(); + let rotation = bounds(&render(0.5, 0.0, 90.0)).height(); + assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}"); + assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}"); + assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}"); +} + #[test] fn tints_colorization_uses_stroke_colour() { let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); @@ -953,6 +1033,165 @@ fn stain_mixes_type_strokes_too() { assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]); } +/// A scatter brush of rectangles filled `fill`, with `colorization` and `hue_jitter`. +fn jittered(fill: Color, colorization: Colorization, hue_jitter: f64) -> Brush { + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(Paint::solid(fill)); + Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization, hue_jitter, ..Default::default() }) } +} + +/// The fill color of each copy. +fn fill_colors(out: &[Node]) -> Vec { + out.iter().map(|n| n.appearance.fill_paint().color().unwrap()).collect() +} + +/// How far hue `h` is from `from`, in degrees, either way round. +fn hue_gap(h: f32, from: f32) -> f32 { + let d = (h - from).rem_euclid(360.0); + d.min(360.0 - d) +} + +#[test] +fn hue_jitter_turns_each_copy_the_same_every_time() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let b = jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 90.0); + let out = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(out.len(), 20); + assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors"); + let colors = fill_colors(&out); + let hues: Vec = colors.iter().map(|c| c.to_hsb()[0]).collect(); + assert!(hues.iter().all(|h| hue_gap(*h, 0.0) <= 90.01), "{hues:?}"); + assert!(hues.iter().any(|h| hue_gap(*h, 0.0) > 10.0), "the copies turn: {hues:?}"); + let distinct: std::collections::HashSet = colors.iter().map(Color::to_hex).collect(); + assert!(distinct.len() > 10, "each copy turns by its own amount: {distinct:?}"); + // Saturation and brightness stay; the copies stay where they were, at their size and angle. + assert!(colors.iter().all(|c| near(f64::from(c.to_hsb()[1]), 1.0, 1e-3) && near(f64::from(c.to_hsb()[2]), 1.0, 1e-3)), "{colors:?}"); + let plain = stroke_pieces(&doc, &jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 0.0), &path, &stroke(1.0)); + let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(); + assert_eq!(boxes(&out), boxes(&plain)); + // Another path draws other amounts. + let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0))); + assert_ne!(other, colors); +} + +#[test] +fn hue_jitter_of_zero_changes_nothing() { + let red = Color::rgb(1.0, 0.0, 0.0); + let out = stroke_pieces(&Document::new(1.0, 1.0), &jittered(red, Colorization::None, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == red)); + // A brush without hue jitter is saved as before, and one saved before reads as 0. + let v = serde_json::to_value(jittered(red, Colorization::None, 0.0)).unwrap(); + assert!(v.get("hue_jitter").is_none(), "{v}"); + let mut old = serde_json::to_value(jittered(red, Colorization::None, 45.0)).unwrap(); + assert_eq!(old.as_object_mut().unwrap().remove("hue_jitter"), Some(serde_json::json!(45.0))); + let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, 0.0, "a brush saved without the key reads as 0"); + let mut with = v.clone(); + with["hue_jitter"] = serde_json::json!(45.0); + let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, 45.0); + // Values outside 0..180 are clamped. + for (given, kept) in [(500.0, 180.0), (-20.0, 0.0)] { + let mut v = v.clone(); + v["hue_jitter"] = serde_json::json!(given); + let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, kept, "{given}"); + } +} + +#[test] +fn hue_jitter_turns_after_the_colorization() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + // Tints: black art takes the blue stroke color, which then turns. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + let hues: Vec = + fill_colors(&stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 30.0), &path, &blue)).iter().map(|c| c.to_hsb()[0]).collect(); + assert!(!hues.is_empty() && hues.iter().all(|h| hue_gap(*h, 240.0) <= 30.01), "{hues:?}"); + assert!(hues.iter().any(|h| hue_gap(*h, 240.0) > 3.0), "{hues:?}"); + // A gray stroke color has no hue: its tints stay as they are. + let gray = StrokeLayer::new(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0); + let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &gray); + let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &gray); + assert_eq!(fill_colors(&turned), fill_colors(&still)); + // Nor does black ink alone, nor a gray, as a process stroke color. + for key in [Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4)] { + let key = StrokeLayer::new(Paint::solid(key), 1.0); + let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &key); + let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &key); + assert_eq!(fill_colors(&turned), fill_colors(&still), "{key:?}"); + } + // A turned process color stays a process color, turned over its C, M and Y with its K kept. + let cmyk = fill_colors(&stroke_pieces(&doc, &jittered(Color::cmyk(0.0, 1.0, 1.0, 0.25), Colorization::None, 60.0), &path, &stroke(1.0))); + assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 1.0, 1.0, 0.25)), "{cmyk:?}"); + for c in &cmyk { + let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") }; + assert_eq!(k, 0.25); + // Full ink in one channel and none in another, as the color before it. + assert!(near(f64::from(c.max(m).max(y)), 1.0, 1e-4) && near(f64::from(c.min(m).min(y)), 0.0, 1e-4), "{c} {m} {y}"); + } + // An RGB color keeps its saturation and brightness in its own values. + let rgb = fill_colors(&stroke_pieces(&doc, &jittered(Color::rgb(0.8, 0.2, 0.4), Colorization::None, 90.0), &path, &stroke(1.0))); + for c in &rgb { + let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") }; + assert!(near(f64::from(r.max(g).max(b)), 0.8, 1e-4) && near(f64::from(r.min(g).min(b)), 0.2, 1e-4), "{c:?}"); + } + // A Lab color keeps its lightness and chroma. + let lab = fill_colors(&stroke_pieces(&doc, &jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 90.0), &path, &stroke(1.0))); + assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}"); + for c in &lab { + let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") }; + assert!(l == 50.0 && near(f64::from(a.hypot(b)), 50.0, 1e-3), "{c:?}"); + } +} + +/// Hue jitter turns type's characters, the colors Tints and Shades and Hue Shift give, and a color +/// linked to a swatch (which loses the link); a pattern paint stays. +#[test] +fn hue_jitter_turns_type_every_colorization_and_linked_colors() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let typed = |hue_jitter| Brush { + name: "s".into(), + kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), hue_jitter, ..Default::default() }), + }; + let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0))); + let turned = run_paints(&stroke_pieces(&doc, &typed(90.0), &path, &stroke(1.0))); + assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}"); + assert_eq!(turned.len(), still.len()); + assert!(turned.iter().any(|p| *p != (red.clone(), red.clone())), "the characters turn: {turned:?}"); + assert!(turned.iter().all(|(f, s)| f == s), "a copy's character fill and stroke turn by the same amount: {turned:?}"); + // Tints and Shades and Hue Shift: the colors they give turn. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + for colorization in [Colorization::TintsAndShades, Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }] { + let art = Color::rgb(1.0, 0.0, 0.0); + let still = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 0.0), &path, &blue)); + let turned = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 45.0), &path, &blue)); + assert_eq!(turned.len(), still.len()); + assert_ne!(turned, still, "{colorization:?}"); + for (t, s) in turned.iter().zip(&still) { + assert!(hue_gap(t.to_hsb()[0], s.to_hsb()[0]) <= 45.01, "{colorization:?}: {t:?} from {s:?}"); + } + } + // A color linked to a swatch turns and loses the link; a pattern paint stays. + let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 1.0 }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + art.appearance.set_stroke(pattern.clone()); + let b = |hue_jitter| Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art: art.clone(), hue_jitter, ..Default::default() }) }; + let still = stroke_pieces(&doc, &b(0.0), &path, &stroke(1.0)); + let turned = stroke_pieces(&doc, &b(90.0), &path, &stroke(1.0)); + assert!(!still.is_empty() && still.iter().all(|n| n.appearance.fill_paint() == linked)); + assert_eq!(turned.len(), still.len()); + for n in &turned { + assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint()); + assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern)); + } +} + /// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its /// swatch links. #[test] diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index eafb4616f1..8aefe61a0d 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -7,6 +7,8 @@ //! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG //! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per //! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`]. +//! [`export_drawings`] writes one such drawing for each of several regions, applying the live +//! effects once for all of them. //! //! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns, //! clipping) is approximated or left out, and each such loss comes back as a warning. @@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive = 1e-6..=1e6; /// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template /// layers, guides and hidden objects are left out. pub fn export(doc: &Document, opts: &DxfOptions) -> Result { + Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default()) +} + +/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as +/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied +/// once for all the drawings. +pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result, String> { + export_drawings_with(doc, opts, drawings, bake_for_drawings) +} + +/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when +/// nothing changes. +fn bake_for_drawings(doc: &Document) -> Option { + // Symbols' art is placed without clipping, as the scene places it. + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + vectorcraft_effects::bake_document_placing_symbols(doc, false, layers) +} + +/// [`export_drawings`] with `bake` applying the live effects. +fn export_drawings_with( + doc: &Document, + opts: &DxfOptions, + drawings: &[(Rect, bool)], + bake: impl Fn(&Document) -> Option, +) -> Result, String> { if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) { return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale)); } - let r = opts.region; - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) { return Err("the export region is not finite".into()); } - // Symbols' art is placed without clipping, as the scene places it. - let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; - let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + if drawings.is_empty() { + return Ok(vec![]); + } + let baked = bake(doc); let doc = baked.as_ref().unwrap_or(doc); - Ok(scene::Scene::new(doc, opts).run()) + Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect()) } #[cfg(test)] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index dda09a0696..797223b688 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() { assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); } } + +/// One drawing written by applying the live effects for it alone and walking the result, as each +/// drawing of a multi-drawing export was written before [`export_drawings`]. +fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput { + let baked = crate::bake_for_drawings(doc); + crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run() +} + +/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes. +type Written = (Vec, Vec<(String, Vec)>, Vec, Vec); + +/// Every field of a written drawing, for comparing two. +fn written(out: &DxfOutput) -> Written { + let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect(); + (out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone()) +} + +/// A Transform effect that moves its object `x` pt right. +fn moved_by(mut n: Node, x: f64) -> Node { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true }); + n +} + +/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect +/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image. +fn drawings_doc() -> Document { + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 2, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 128, 255, 255].repeat(4), + ) + .unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); + let mut d = doc_with(|d| { + let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY }); + instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into(); + let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + faint.opacity = 0.5; + faint.blend = vectorcraft_color::BlendMode::Multiply; + let im = ImageObject { + key: "raster-1".into(), + width: 2, + height: 2, + xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))] + }); + let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d +} + +#[test] +fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() { + let d = drawings_doc(); + assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply"); + // The left and right halves cropped, the whole page uncropped, and a region off the page. + let drawings = [ + (Rect::new(0.0, 0.0, 100.0, 100.0), true), + (Rect::new(100.0, 0.0, 200.0, 100.0), true), + (Rect::new(0.0, 0.0, 200.0, 100.0), false), + (Rect::new(300.0, 0.0, 400.0, 100.0), true), + ]; + // With every option, and with images and hatches left out (which adds setting notes). + let all_in = opts(&d); + for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] { + let bakes = std::cell::Cell::new(0); + let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }) + .unwrap(); + assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing"); + assert_eq!(outs.len(), drawings.len()); + for ((region, crop), out) in drawings.iter().zip(&outs) { + let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }); + assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}"); + let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap(); + assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}"); + } + let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect(); + assert_eq!(public, outs.iter().map(written).collect::>()); + // The halves hold different art, the left half a line with losses, and the region off the + // page nothing. + assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty()); + assert_ne!(outs[0].bytes, outs[1].bytes); + assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty()); + if o.include_images { + assert_eq!(outs[2].images.len(), 1); + } else { + assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty()); + } + } +} + +#[test] +fn drawings_are_checked_before_the_live_effects_are_applied() { + let d = drawings_doc(); + let o = opts(&d); + let bakes = std::cell::Cell::new(0); + let count = |doc: &Document| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }; + let page = (d.artboards[0].rect, false); + let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false); + assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite"); + let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err(); + assert!(e.starts_with("scale must be a number"), "{e}"); + assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty()); + assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none"); +} + +/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`. +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by +/// drawing with the effects applied for each (as before [`export_drawings`]) and with +/// [`export_drawings`], alternating, seven times each, and check that both write the same +/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of +/// wall-clock time. +/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn dxf_artboards_bake_perf() { + const BOARDS: usize = 8; + let mut d = Document::new(200.0 * BOARDS as f64, 200.0); + let layer = d.layers[0].id; + let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let mut art = vec![]; + for i in 0..50 { + let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0); + art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5))); + } + let mut cell = Node::group(d.alloc_id(), art); + cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"}))); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) }); + for b in 0..BOARDS { + let x0 = 200.0 * b as f64; + for i in 0..250 { + let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0); + let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5); + let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i}); + n.appearance.effects.push(effect("distort.roughen", params)); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + for i in 0..20 { + let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0)); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf }); + d.insert(Some(layer), usize::MAX, instance).unwrap(); + } + } + let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() }; + let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect(); + let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::>(); + let after = || export_drawings(&d, &o, &drawings).unwrap(); + let time = |f: &dyn Fn() -> Vec| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + let outs = f(); + let wall = wall.elapsed().as_secs_f64() * 1000.0; + let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6); + (outs, cpu, wall) + }; + let (mut runs_before, mut runs_after) = (vec![], vec![]); + for _ in 0..7 { + let (a, cpu_a, wall_a) = time(&before); + let (b, cpu_b, wall_b) = time(&after); + assert_eq!(a.len(), BOARDS); + assert_eq!(a.iter().map(written).collect::>(), b.iter().map(written).collect::>(), "both write the same drawings"); + runs_before.push((cpu_a, wall_a)); + runs_after.push((cpu_b, wall_b)); + } + let median = |runs: &[(Option, f64)], cpu: bool| { + let mut v: Vec = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied() + }; + for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] { + println!( + "{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}", + median(runs, true), + median(runs, false) + ); + } +} diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 3ad4820ce1..96640b5508 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 { /// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`] /// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the /// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their -/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user +/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper +/// as the media white point; the colorimetric Lab → CMYK table without black-point +/// compensation, the perceptual and saturation ones with it); a profile the user /// loaded is the file it came from. Cached. pub fn icc_bytes(name: &str) -> Result, CmsError> { static CACHE: Mutex)>> = Mutex::new(Vec::new()); @@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result, CmsError> { let bytes: Arc<[u8]> = if name == GRAY { icc::encode(&icc::gray_profile(name))? } else if BUILTIN_CMYK.contains(&name) { - let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?; - icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? + // The perceptual and saturation tables map the shadows with black-point compensation; the + // colorimetric table is the inverse of the CMYK → Lab table, without it. + let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?; + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?; + let paper = match &cms.cmyk { + CmykSpace::Generic(g) => g.paper_xyz(), + CmykSpace::Device | CmykSpace::Icc(_) => lab::D50, + }; + let to_lab = |c| cms.cmyk_to_lab(c); + let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric); + icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? } else { icc::builtin_rgb_bytes(name)? } diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 3d532ac02a..16f251054b 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -133,6 +133,11 @@ pub struct GenericCmyk { } impl GenericCmyk { + /// Absolute XYZ (D50) of the paper. + pub fn paper_xyz(&self) -> [f32; 3] { + self.paper_xyz + } + pub fn new(params: GenericCmykParams) -> Self { let paper_xyz = lab_to_xyz(params.paper); let mut prim = [D50; 16]; diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index ffddd6c955..8fc287ae23 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -446,11 +446,20 @@ const B2A_GRID: usize = 17; const GAMUT_GRID: usize = 9; /// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a -/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding). +/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped, +/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the +/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag. /// It carries every tag ICC.1 requires of an output profile: the tables for all three intents /// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK -/// TIFF that embedded one, #2707). -pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile { +/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which +/// the ICC-absolute colorimetric intent reproduces. +pub(super) fn cmyk_profile( + name: &str, + paper: [f32; 3], + to_lab: impl Fn([f32; 4]) -> lab::Lab, + mapped: impl Fn(lab::Lab) -> [f32; 4], + colorimetric: impl Fn(lab::Lab) -> [f32; 4], +) -> ColorProfile { let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32; let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3); @@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr let l = to_lab(cmyk); a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q)); } - let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); - for i in 0..B2A_GRID.pow(3) { - let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); - b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); - } + let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| { + let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); + for i in 0..B2A_GRID.pow(3) { + let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); + b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); + } + b2a + }; + let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric)); // Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut. let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3)); for i in 0..GAMUT_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID)); let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0); - gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX }); + gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX }); } let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n]; let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| { @@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr }) }; let a2b = table(4, 3, A2B_GRID, a2b); + let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped); let b2a = table(3, 4, B2A_GRID, b2a); let gamut = table(3, 1, GAMUT_GRID, gamut); let mut p = ColorProfile::default(); @@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr p.pcs = DataColorSpace::Lab; p.rendering_intent = RenderingIntent::RelativeColorimetric; p.white_point = moxcms::WHITE_POINT_D50.to_xyzd(); - p.media_white_point = Some(p.white_point); + p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2]))); p.lut_a_to_b_perceptual = Some(a2b.clone()); p.lut_a_to_b_saturation = Some(a2b.clone()); p.lut_a_to_b_colorimetric = Some(a2b); - p.lut_b_to_a_perceptual = Some(b2a.clone()); - p.lut_b_to_a_saturation = Some(b2a.clone()); + p.lut_b_to_a_perceptual = Some(b2a_mapped.clone()); + p.lut_b_to_a_saturation = Some(b2a_mapped); p.lut_b_to_a_colorimetric = Some(b2a); p.gamut = Some(gamut); labelled(p, name) diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index bee0f0f9fa..2c1d96638b 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() { let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got)); assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})"); } - // And back: an in-gamut colour separates to about the same inks. - let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false); - let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); - let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); - assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}"); + // And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is + // the colorimetric inverse of the CMYK → Lab table, with no black-point compensation. + for inks in [ + [0.1, 0.6, 0.8, 0.0], + [0.5, 0.1, 0.3, 0.1], + [0.3, 0.3, 0.3, 0.2], + [0.05, 0.05, 0.4, 0.0], + [0.4, 0.3, 0.3, 0.6], + [0.6, 0.5, 0.5, 0.4], + [0.2, 0.2, 0.2, 0.8], + [0.0, 0.0, 0.0, 0.5], + ] { + let srgb = cms.cmyk_to_srgb(inks, false); + let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); + let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); + let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)); + assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})"); + } + // The perceptual table keeps black-point compensation: source black separates to inks + // that print the press's black point, as the CMS separates it with compensation. + let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap(); + let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric); + let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap(); + let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]); + let de = delta_e2000(printed(&want), printed(&got)); + assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want)); + } +} + +#[test] +fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() { + // CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto + // RGB, which holds every color these profiles print, so no display gamut clips the inks. + // Inks that print outside sRGB come back to inks that print the same color. + for name in BUILTIN_CMYK { + let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap(); + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap(); + for inks in + [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]] + { + let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap(); + let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]])); + // Within the ΔE of 3 that the gamut tag counts as reproduced. + assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})"); + } + } +} + +#[test] +fn cmyk_profiles_carry_their_paper_as_the_media_white() { + let generic = generic::swop_like(); + let p = parse(&icc_bytes(GENERIC_CMYK).unwrap()); + let white = p.media_white_point.unwrap(); + let paper = lab::lab_to_xyz(generic.paper); + for (got, want) in [white.x, white.y, white.z].iter().zip(paper) { + assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}"); } } @@ -116,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() { let rich = [0.75, 0.68, 0.67, 0.9]; let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric)); // Without compensation the profile's black is a dark grey; with it, rich black goes most of - // the way to RGB black (not all: it isn't quite the darkest ink the profile prints). + // the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the + // profile's Lab → CMYK table carries no compensation of its own). assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}"); - assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}"); + assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}"); // The screen shows what an sRGB conversion writes, compensated alike. let srgb = |bpc| { let c = icc_cmyk(bpc); diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 3bfba32f6a..737e10eb58 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -143,6 +143,11 @@ impl Appearance { pub fn fill_paint(&self) -> Paint { self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None) } + /// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this + /// includes lower fills in the stack; zero opacity still counts for selecting its geometry. + pub fn has_visible_fill(&self) -> bool { + self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none())) + } pub fn stroke_paint(&self) -> Paint { self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None) } diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index e803d867fc..9e78d17d4d 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -112,6 +112,18 @@ pub enum ArrowStyle { None, } +impl ArrowStyle { + /// The stroke arrowhead drawn at each end of the dimension line, or None for no head. + pub fn arrowhead(self) -> Option { + match self { + Self::Filled => Some(crate::Arrowhead::Triangle), + Self::Open => Some(crate::Arrowhead::TriangleOpen), + Self::Tick => Some(crate::Arrowhead::Slash), + Self::None => None, + } + } +} + /// Where the label sits across the dimension line. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f4a307cd5c..4365f7788a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -339,6 +339,7 @@ impl Document { /// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in /// tree order where `id` appears. pub fn index_path(&self, id: NodeId) -> Option> { + crate::id_index::note_path_lookup(); // The cached path, while the node there still has the id ([`id_index`]). let cached = self.index.get(); match cached.as_ref().and_then(|m| m.get(&id)) { @@ -423,6 +424,44 @@ impl Document { out } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike + /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every + /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still + /// checks out, the nodes are found along those paths; otherwise one walk of the tree finds + /// them. As for every cached lookup, a second node given an existing id after the cache was + /// built is not found while the first one's cached path checks out (see [`id_index`]). + pub fn nodes_in_order(&self, ids: impl IntoIterator) -> Vec<&Node> { + let want: std::collections::HashSet> = ids.into_iter().collect(); + // As in `index_paths`, one walk is quicker than checking the cached paths of a good share + // of the document. + if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let mut paths = Vec::with_capacity(want.len()); + let cached = want.iter().all(|id| match cache.get(id) { + Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + paths.push(p); + true + } + _ => false, + }); + if cached { + // A node's path sorts after the paths of the nodes before it in tree order, its + // ancestors included. + paths.sort_unstable(); + return paths.iter().filter_map(|p| self.node_at(p)).collect(); + } + } + let mut out = Vec::new(); + if !want.is_empty() { + crate::id_index::note_tree_walk(); + self.walk(|n| { + if want.contains(&n.id) { + out.push(n); + } + }); + } + out + } + /// The node at index path `path` (as [`Document::index_path`] gives it). pub fn node_at(&self, path: &[usize]) -> Option<&Node> { let (first, rest) = path.split_first()?; 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/hit.rs b/crates/doc/src/hit.rs index 3b415ef1ed..83b2a60446 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -82,8 +82,9 @@ impl Default for HitOptions { } } -/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or -/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated +/// The shapes that an image's own fills and strokes paint, or the fills and strokes of the art of a +/// symbol instance whose own fill or stroke has a geometry effect, each with its fill rule and the +/// fill or stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated /// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and /// patterns in the document it is given. pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>; @@ -97,10 +98,58 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } -/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while -/// nothing is registered. -pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n)) +/// The shapes that [`ImagePaint`] gives for one object. +type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; + +/// The shapes that the image or symbol instance `n` paints with its geometry effects +/// ([`set_image_paint`]), none while nothing is registered. The shapes of a symbol instance of +/// `doc` with an effect on a fill or stroke are kept on this thread ([`PAINT_KEPT`]) and measured +/// again when `n`, a symbol of `doc` or its 9-slice guides or natural size, a pattern of `doc`, +/// its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every call while `n` or the document's symbols or +/// patterns hold a placed document or the symbols hold an image ([`symbols_hold_images`]). +pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Rc { + let Some(f) = IMAGE_PAINT.get() else { return Rc::default() }; + let row_effects = || n.appearance.items.iter().any(|i| !i.effects().is_empty()); + let Some(d) = doc.filter(|_| matches!(n.kind, NodeKind::SymbolInstance { .. }) && row_effects()) else { + return Rc::new(f(doc, n)); + }; + let inputs = live_inputs(); + if let Some(painted) = kept(&PAINTED, d, n, inputs) { + return painted; + } + #[cfg(test)] + PAINT_EVALUATED.with(|c| c.set(c.get() + 1)); + let painted = Rc::new(f(doc, n)); + if !symbols_hold_images(d) { + let size = painted.iter().fold(0usize, |s, (bp, _, _)| s.saturating_add(1 + bp.elements().len())); + keep(&PAINTED, d, n, inputs, &painted, size, PAINT_KEPT); + } + painted +} + +/// Does the art of a symbol of `doc` hold an image? The shapes its fills and strokes paint can +/// follow its pixels, which change when its file is read again, so [`image_paint`] does not keep +/// the shapes of an instance then. +fn symbols_hold_images(doc: &Document) -> bool { + let mut image = false; + doc.symbols.iter().for_each(|s| s.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_)))); + image +} + +/// How many symbol instances' shapes [`image_paint`] keeps on each thread: every click and every +/// hover measures each instance whose fill or stroke has a geometry effect. +const PAINT_KEPT: usize = 64; + +thread_local! { + /// The shapes [`image_paint`] keeps, the latest first. + static PAINTED: RefCell>> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many symbol instances [`image_paint`] measured on this thread. + static PAINT_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// One level of evaluation of a live object in a document, as the canvas draws it: type in an @@ -127,21 +176,72 @@ fn live_inputs() -> u64 { LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) } -/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by -/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art -/// and its [`art_size`]. -struct EvaluatedLive { +/// An object evaluated by [`live_art`] or [`image_paint`] on this thread: the object, its +/// document's symbols (by name and art), patterns, swatches and color groups, the document data +/// that symbols' 9-slice guides and natural sizes are kept in, and the [`LiveInputs`] as they +/// were, the result and its size. +struct Evaluated { node: Node, symbols: Vec<(String, Arc)>, patterns: Vec, swatches: crate::Shared>, swatch_groups: crate::Shared>, + unknown: crate::Shared>, inputs: u64, - art: Rc>, + art: Rc, size: usize, } -impl EvaluatedLive { +/// The evaluations kept on this thread in one store, the latest first. +type Store = std::thread::LocalKey>>>; + +/// The evaluation of `n` in `doc` with inputs `inputs` that `store` keeps, moved to the front. +fn kept(store: &'static Store, doc: &Document, n: &Node, inputs: u64) -> Option> { + store.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; + let e = kept.remove(i); + let art = e.art.clone(); + kept.insert(0, e); + Some(art) + }) +} + +/// Keep `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, at the front +/// of `store`, which keeps `most` evaluations whose sizes add up to [`LIVE_KEPT_SIZE`] at most. +/// Nothing is kept when `art` alone is larger, or when `n` or the document's symbols or patterns +/// hold a placed document ([`holds_placed`]). +fn keep(store: &'static Store, doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize, most: usize) { + if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { + return; + } + let e = Evaluated::new(doc, n, inputs, art, size); + store.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(most); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); +} + +impl Evaluated { + /// `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, as they are now. + fn new(doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize) -> Self { + Self { + node: n.clone(), + symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), + patterns: doc.patterns.clone(), + swatches: doc.swatches.clone(), + swatch_groups: doc.swatch_groups.clone(), + unknown: doc.unknown.clone(), + inputs, + art: art.clone(), + size, + } + } + /// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now? fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool { self.inputs == inputs @@ -151,6 +251,7 @@ impl EvaluatedLive { && self.patterns == doc.patterns && self.swatches == doc.swatches && self.swatch_groups == doc.swatch_groups + && self.unknown == doc.unknown } } @@ -158,8 +259,9 @@ impl EvaluatedLive { /// envelope's stroke band hits it again and again, and an envelope can hold a blend. const LIVE_KEPT: usize = 4; -/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than -/// this is not kept. +/// Most size the evaluations [`live_art`] keeps on one thread add up to ([`art_size`]), and the +/// shapes [`image_paint`] keeps (each shape and its path elements). Art larger than this is not +/// kept. const LIVE_KEPT_SIZE: usize = 250_000; /// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths. @@ -184,52 +286,23 @@ fn holds_placed(doc: &Document, n: &Node) -> bool { thread_local! { /// The evaluations [`live_art`] keeps, the latest first. - static EVALUATED: RefCell> = const { RefCell::new(Vec::new()) }; + static EVALUATED: RefCell>>> = const { RefCell::new(Vec::new()) }; } /// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while -/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of -/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every +/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc` or its 9-slice +/// guides or natural size, a pattern of `doc`, its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every /// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]). fn live_art(doc: &Document, n: &Node) -> Rc> { let inputs = live_inputs(); - let kept = EVALUATED.with_borrow_mut(|kept| { - let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; - let e = kept.remove(i); - let art = e.art.clone(); - kept.insert(0, e); - Some(art) - }); - if let Some(art) = kept { + if let Some(art) = kept(&EVALUATED, doc, n, inputs) { return art; } #[cfg(test)] LIVE_EVALUATED.with(|c| c.set(c.get() + 1)); let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n))); - let size = art_size(&art); - if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { - return art; - } - let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); - let e = EvaluatedLive { - node: n.clone(), - symbols, - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; - EVALUATED.with_borrow_mut(|kept| { - kept.insert(0, e); - kept.truncate(LIVE_KEPT); - let mut total = 0usize; - kept.retain(|e| { - total = total.saturating_add(e.size); - total <= LIVE_KEPT_SIZE - }); - }); + keep(&EVALUATED, doc, n, inputs, &art, art_size(&art), LIVE_KEPT); art } @@ -257,7 +330,7 @@ pub fn set_drawn_art(f: DrawnArt) { /// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and /// the box round everything that art can paint. struct EvaluatedDrawn { - of: EvaluatedLive, + of: Evaluated>, reach: Option, } @@ -310,7 +383,8 @@ fn plain(mask: bool, f: impl FnOnce() -> T) -> T { /// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated /// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a /// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the -/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and +/// document or its 9-slice guides or natural size, its patterns, swatches or color groups, or the +/// [`LiveInputs`] have changed since, and /// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new /// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is /// kept alone. @@ -332,16 +406,7 @@ fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option let art = Rc::new(art.into_iter().collect::>()); let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n))); if !holds_placed(doc, n) { - let of = EvaluatedLive { - node: n.clone(), - symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; + let of = Evaluated::new(doc, n, inputs, &art, size); DRAWN.with_borrow_mut(|(kept, total)| { if let Some(old) = kept.remove(&n.id) { *total = total.saturating_sub(old.of.size); @@ -607,9 +672,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option< /// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found. fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { - // Each round leaves out the objects found so far (and everything inside them). - while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { - if tops.contains(&top) { + // Each round leaves out the objects found so far (and everything inside them). `found` holds + // the same ids as `tops`, which keeps their order. + let mut found: HashSet = tops.iter().copied().collect(); + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) { + if !found.insert(top) { break; } tops.push(top); @@ -1290,8 +1357,9 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom:: stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline) } -/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a -/// miter or square cap, so the caller falls back to the full stroke check there. +/// Check the body without assembling a `BezPath`. Near an end or joint, the caller uses the +/// full stroke check for non-round caps or joins: Butt and Bevel can reject a radial body hit, +/// while Miter and Square can extend beyond it. fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> { if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 { return None; @@ -1349,6 +1417,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } match &n.kind { NodeKind::Path { path, rule, .. } => { + let has_fill = n.appearance.has_visible_fill(); if opt.outline && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) { @@ -1361,7 +1430,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } let mut strokes = n.appearance.painted_strokes(); if !opt.outline - && n.appearance.fill().is_none_or(|f| f.paint.is_none()) + && !has_fill && let Some(s) = strokes.next() && strokes.next().is_none() && s.align == StrokeAlign::Center @@ -1376,10 +1445,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio path, p, s.width / 2.0 + opt.tol, - if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 }, + if s.join != crate::LineJoin::Round || s.cap != crate::LineCap::Round { s.reach() + opt.tol } else { 0.0 }, ) { - if hit { + if hit && !near_decoration { return Some(HitKind::Stroke); } if !near_decoration { @@ -1390,8 +1459,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) { return Some(k); } - let filled = !n.appearance.fill_paint().is_none(); - if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) { + if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) { return Some(HitKind::Fill); } None @@ -1412,7 +1480,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { return Some(HitKind::Outline); } - (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) + (!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { @@ -1436,22 +1504,21 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if opt.outline { return None; } - image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { - AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), - AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), - }) + hit_painted(n, p, opt, symbols) } NodeKind::Text(_) | NodeKind::PlacedDocument(_) => { n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } // A symbol instance is hit within its bounds, and outside them where its art paints - // ([`instance_art_hit`]). In the art of another instance walked outside that instance's - // bounds, it is hit only where its own art paints ([`ArtOnly`]). + // ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape + // the art it draws ([`image_paint`]) except in outline mode. In the art of another instance + // walked outside that instance's bounds, it is hit only where its own art paints + // ([`ArtOnly`]). NodeKind::SymbolInstance { .. } => { if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { return Some(HitKind::Bounds); } - instance_art_hit(n, p, opt, symbols) + instance_art_hit(n, p, opt, symbols).or_else(|| if opt.outline { None } else { hit_painted(n, p, opt, symbols) }) } // A blend or an envelope is hit within its bounds, and outside them where its evaluated // art paints: a blend's keys and steps on a spine can reach past the keys and the spine, @@ -1478,6 +1545,16 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } } +/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a +/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a +/// stroke along its shape, a fill inside it except with Selection by Path Only. +fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { + AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), + AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), + }) +} + /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path /// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and /// type on a path's path, drawn through `n`'s perspective projection if it has one. @@ -2019,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving /// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured /// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are -/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a +/// touched where the live geometry effects of a clipping path in their art show it, or where the +/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except +/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a /// clipping mask counts only when the marquee meets the region its clipping path clips to, and then /// only within that region's bounds. In isolation mode the clipping mask of the isolated container, /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit @@ -2027,20 +2106,39 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// the members of a group or layer with geometry effects of its own, are touched where the art those /// effects draw lies ([`set_drawn_art`]), as clicks hit them. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false, false) + marquee_with(doc, r, scope, leaves, false, false, false) } /// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer /// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as -/// the clicks of [`HitOptions::outline`] do. -pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false, outline) +/// the clicks of [`HitOptions::outline`] do. With `skip_guides` (Lock Guides is on or the guides +/// are hidden, as [`HitOptions::skip_guides`]), the paths made into guides are not touched, at the +/// top or inside a group, so a group is not taken for a guide in it (#8538). +pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool, skip_guides: bool) -> Vec { + marquee_with(doc, r, scope, leaves, false, outline, skip_guides) } /// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group /// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint. -pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool) -> Vec { - marquee_with(doc, r, scope, true, true, outline) +pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool, skip_guides: bool) -> Vec { + marquee_with(doc, r, scope, true, true, outline, skip_guides) +} + +/// What a marquee ([`marquee_with`]) takes, besides where it is: whether a compound path is +/// touched by every path it paints (`whole_compounds`, for an enclosing loop's candidates), and +/// whether the paths made into guides are left out (`skip_guides`: Lock Guides is on or the +/// guides are hidden, [`HitOptions::skip_guides`] for the marquee). +#[derive(Clone, Copy)] +struct Rules { + whole_compounds: bool, + skip_guides: bool, +} + +impl Rules { + /// Is `n` a path made into a guide that the marquee leaves out? + fn skips(self, n: &Node) -> bool { + self.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. }) + } } /// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)? @@ -2048,8 +2146,17 @@ fn previews_off(n: &Node) -> bool { matches!(n.kind, NodeKind::Layer { preview: false, .. }) } -fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { +fn marquee_with( + doc: &Document, + r: Rect, + scope: Option, + leaves: bool, + whole_compounds: bool, + outline: bool, + skip_guides: bool, +) -> Vec { let _walk = ArtWalk::open(); + let rules = Rules { whole_compounds, skip_guides }; let mut out = Vec::new(); // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. let locks = doc.locked_artboards_kept(); @@ -2063,7 +2170,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh Some(c) => { // In an isolated clip group, its members by their own geometry, as clicks take // them ([`edits_inside`]). - let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) }; + let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, rules, outline || previews_off(s)) }; c.iter() .enumerate() .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) @@ -2085,7 +2192,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh .layers .iter() .filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id)) - .flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None)) + .flat_map(|l| layer_objects(l, &symbols, r, outline, rules, None)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of @@ -2094,17 +2201,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object /// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around /// `l` has such effects. - fn layer_objects<'a>( - l: &'a Node, - s: &SymbolBoxes, - r: Rect, - outline: bool, - whole_compounds: bool, - drawn: Option>>, - ) -> Vec> { + fn layer_objects<'a>(l: &'a Node, s: &SymbolBoxes, r: Rect, outline: bool, rules: Rules, drawn: Option>>) -> Vec> { let mut out = vec![]; let outline = outline || previews_off(l); - let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline)); + let drawn = drawn.or_else(|| touched_in_art(l, s, r, rules, outline)); let inner = marquee_in_parent(l, r, outline); for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { @@ -2113,7 +2213,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh && !c.locked && !c.is_template() { - out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone())); + out.extend(layer_objects(c, s, inner, outline, rules, drawn.clone())); } } else if !c.is_ruler_guide() { if drawn.is_some() { @@ -2130,12 +2230,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// The ids of the objects of the art that group or layer `n` draws with its own geometry /// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them. /// `None` in outline and when it has no such effects. - fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option>> { + fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules, outline: bool) -> Option>> { let art = drawn_art(s, n, outline)?; let _off = DrawnOff::set(); let mut ids = vec![]; for a in art.iter().filter(|a| a.visible) { - collect_leaves(a, s, r, None, whole_compounds, false, &mut ids); + collect_leaves(a, s, r, None, rules, false, &mut ids); } Some(Rc::new(ids.into_iter().collect())) } @@ -2188,14 +2288,20 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// compound paths, layers and groups are touched by their box. A clipping path is touched by - /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). - fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { + /// compound paths, layers and groups are touched by their box, and an image or a symbol + /// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping + /// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region + /// ([`clip_edge_touches`]). + fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, rules: Rules, outline: bool) -> bool { + // Locked or hidden guides are not touched ([`Rules::skips`]). + if rules.skips(n) { + return false; + } // A path or compound path whose geometry effects reshape it, or a group or layer whose own // geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]). if let Some(art) = drawn_art(s, n, outline || previews_off(n)) { let _off = DrawnOff::set(); - return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false)); + return art.iter().any(|a| a.visible && touches(a, s, r, None, rules, false)); } match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), @@ -2206,25 +2312,41 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh c.visible && !shaper_hides(n, i, scope) && if i == 0 && n.clips() { - plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))) + plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, rules, outline))) || clip_edge_touches(c, r, outline) } else { - inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) + inner.is_some_and(|r| touches(c, s, r, scope, rules, outline)) } }) } - NodeKind::Compound { children, .. } if whole_compounds => { - children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) + NodeKind::Compound { children, .. } if rules.whole_compounds => { + // Guide contours left out ([`Rules::skips`]) don't make the compound a candidate. + children.iter().filter(|c| !rules.skips(c)).filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) } - NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), - NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), + NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, rules, outline)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, rules, outline)), // A symbol instance is touched by its box, and outside it where the live geometry - // effects of a clipping path in its art show the art. In the art of another instance - // walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]). - NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), + // effects of a clipping path in its art show the art, or where the geometry effects of + // its active fill or stroke reshape the art ([`painted_touches`]). In the art of another + // instance walked outside that instance's box, it is touched only by its own art + // ([`ArtOnly`]) and those shapes. + NodeKind::SymbolInstance { .. } => { + !ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, rules) || painted_touches(n, s, r)) + } + // An image is touched by its box, and outside it where its own fills and strokes paint. + NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r), _ => box_touches(n, s, r), } } + /// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol + /// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is + /// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when + /// `r` meets the reach of `n` ([`Node::reach_bounds_with`]). + fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { + let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; + n.reach_bounds_with(s).is_some_and(meets) + && image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r)) + } /// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of /// a symbol that draws a straight line) is touched where the marquee crosses it. fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { @@ -2238,7 +2360,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the /// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's /// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows. - fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool { + fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false }; let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) { @@ -2255,15 +2377,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh #[cfg(test)] ARTS_WALKED.with(|c| c.set(c.get() + 1)); let _art_only = ArtOnly::set(); - art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false)) + art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, rules, false)) } - fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { + fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, rules: Rules, outline: bool, out: &mut Vec) { match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { let outline = outline || previews_off(n); // The members that the art its own geometry effects draw touches, and a group whose // own fills and strokes that art paints, as clicks hit it ([`member_chain`]). - if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) { + if let Some(drawn) = touched_in_art(n, s, r, rules, outline) { if drawn.contains(&n.id) && !n.is_layer() { out.push(n.id); } @@ -2278,18 +2400,18 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh if i == 0 && n.clips() { let before = out.len(); if let Some(r) = mask_marquee(n, r) { - plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out)); + plain(true, || collect_leaves(c, s, r, scope, rules, outline, out)); } if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { out.push(c.id); } } else if let Some(r) = inner { - collect_leaves(c, s, r, scope, whole_compounds, outline, out); + collect_leaves(c, s, r, scope, rules, outline, out); } } } _ => { - if touches(n, s, r, scope, whole_compounds, outline) { + if touches(n, s, r, scope, rules, outline) { out.push(n.id); } } @@ -2324,14 +2446,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh if leaves { let before = out.len(); if let Some(r) = r { - collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out); + collect_leaves(t, &symbols, r, scope, rules, outline, &mut out); } if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) { out.push(t.id); } - } else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline)) - || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) - { + } else if r.is_some_and(|r| touches(t, &symbols, r, scope, rules, outline)) || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) { out.push(t.id); } } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 39efd78795..a38f36f166 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -164,8 +164,8 @@ fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_chang // So with a marquee across the art's left edge: in the view, only in Outline view. The // clipping path's own left edge lies there too, and counts in both. let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); - assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]); - assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, false, false), [mask_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, true, false), [mask_id, art_id]); // `marquee_in` measures by the plain shapes, as its callers clip by them. assert!(marquee_in(d.node(g).unwrap(), edge).is_some()); // Hidden, the effect no longer moves the region. @@ -489,8 +489,8 @@ fn a_marquee_touches_a_paths_shifted_art_not_its_source() { for leaves in [false, true] { assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn"); assert!(marquee(&d, own, None, leaves).is_empty(), "its own place"); - assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art"); - assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place"); + assert!(marquee_in_view(&d, drawn, None, leaves, true, false).is_empty(), "outline: no drawn art"); + assert_eq!(marquee_in_view(&d, own, None, leaves, true, false), [a], "outline: its own place"); } } @@ -870,6 +870,68 @@ fn a_selected_guide_hidden_by_a_mask_counts_only_while_guides_can_be_clicked() { assert_eq!(selected_hidden_at(&d, hidden, HitOptions { skip_guides: true, ..opt }, &[guide_id]), None); } +/// #8538: while guides are locked or hidden (`skip_guides`), a marquee touches no guide path, at +/// the top of a layer or in a group (the group is not taken for it), nor in a group in a group, +/// with leaves or without. The group's other members still take it, and with the guides unlocked +/// the guide does. +#[test] +fn a_marquee_skips_guide_paths_in_groups_while_guides_are_locked() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let guide = |d: &mut Document, r: Rect| { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + n + }; + let top = guide(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0)); + let inner = guide(&mut d, Rect::new(100.0, 0.0, 120.0, 20.0)); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(200.0, 0.0, 220.0, 20.0)), Appearance::default_art()); + let (top_id, inner_id, art_id) = (top.id, inner.id, art.id); + let (outer_id, nested_id) = (d.alloc_id(), d.alloc_id()); + let nested = Node::group(nested_id, vec![Arc::new(inner)]); + d.insert(Some(l), 0, top).unwrap(); + d.insert(Some(l), 1, Node::group(outer_id, vec![Arc::new(nested), Arc::new(art)])).unwrap(); + let (on_top, on_inner, on_art) = (Rect::new(-5.0, 5.0, 5.0, 10.0), Rect::new(95.0, 5.0, 105.0, 10.0), Rect::new(195.0, 5.0, 205.0, 10.0)); + for leaves in [false, true] { + let m = |r: Rect, skip: bool| marquee_in_view(&d, r, None, leaves, false, skip); + assert!(m(on_top, true).is_empty(), "a guide at the top, leaves {leaves}"); + assert!(m(on_inner, true).is_empty(), "a guide in a group in a group, leaves {leaves}"); + assert!(m(Rect::new(0.0, 0.0, 300.0, 200.0), true).iter().all(|id| ![top_id, inner_id].contains(id)), "all, leaves {leaves}"); + assert_eq!(m(on_art, true), [if leaves { art_id } else { outer_id }], "the group's art, leaves {leaves}"); + // Unlocked: the guides are touched. + assert_eq!(m(on_top, false), [top_id], "unlocked, leaves {leaves}"); + assert_eq!(m(on_inner, false), [if leaves { inner_id } else { outer_id }], "unlocked, leaves {leaves}"); + } + // An enclosing loop's candidates leave them out alike. + assert!(enclosure_candidates(&d, on_inner, None, false, true).is_empty()); + assert_eq!(enclosure_candidates(&d, on_inner, None, false, false), [inner_id]); +} + +/// #8538: an enclosing loop's candidates leave out a compound path whose touched contours are all +/// locked or hidden guides, as the marquee does. +#[test] +fn guide_contours_do_not_make_a_compound_an_enclosure_candidate() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let part = |d: &mut Document, r: Rect| { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + Arc::new(n) + }; + let (a, b) = (part(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0)), part(&mut d, Rect::new(20.0, 20.0, 40.0, 40.0))); + let id = d.alloc_id(); + let mut compound = Node::group(id, vec![]); + compound.kind = NodeKind::Compound { children: vec![a, b], rule: Default::default() }; + d.insert(Some(l), 0, compound).unwrap(); + let r = Rect::new(0.0, 0.0, 60.0, 60.0); + assert!(enclosure_candidates(&d, r, None, false, true).is_empty(), "locked or hidden"); + assert_eq!(enclosure_candidates(&d, r, None, false, false), [id], "shown and unlocked"); +} + /// A selected path in a Shaper group's original shapes, where an outer mask hides it, counts only /// while those shapes can be clicked (Construction mode, with them isolated), however deep it /// lies in them. @@ -1262,6 +1324,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { assert_eq!(evaluated(), before + 2); } +/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to +/// (320, 20); nothing for anything else. +fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => { + let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath(); + vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))] + } + _ => vec![], + } +} + +/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once, +/// and again only after the instance or the symbols change. +#[test] +fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() { + set_image_paint(painted_far_away); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) }); + let inst = d.alloc_id(); + let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + n.appearance = Appearance::default_art().into(); + let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true }; + n.appearance.items[0].effects_mut().push(offset); + d.insert(Some(l), 0, n).unwrap(); + let measured = || PAINT_EVALUATED.with(std::cell::Cell::get); + let before = measured(); + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf); + assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints"); + assert_eq!(at(&d, 500.0), None); + assert_eq!(at(&d, 10.0), Some(inst)); + assert_eq!(measured(), before + 1); + d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12}); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 2, "a changed instance is measured again"); + let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3, "changed symbols measure it again"); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3); + // An image's pixels change when its file is read again, so with one in a symbol's art every + // click measures the instance. + let xf = vectorcraft_geom::Affine::IDENTITY; + let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(at(&d, 310.0), Some(inst)); + assert!(measured() >= before + 5, "each click measures it: {}", measured() - before); +} + /// A kept evaluation is the evaluation of the object only while the fonts and plug-ins /// ([`LiveInputs`]) are as they were. #[test] @@ -1274,19 +1390,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() { } /// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art. -fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive { - EvaluatedLive { +fn kept_evaluation(d: &Document, n: &Node) -> Evaluated> { + Evaluated { node: n.clone(), symbols: vec![], patterns: vec![], swatches: d.swatches.clone(), swatch_groups: d.swatch_groups.clone(), + unknown: d.unknown.clone(), inputs: 7, art: std::rc::Rc::new(vec![]), size: 0, } } +/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place +/// the symbol's art, and the document keeps them apart from the symbols. +#[test] +fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() { + let mut d = Document::new(100.0, 100.0); + let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let e = kept_evaluation(&d, &n); + assert!(e.is_of(&d, &n, 7)); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]})); + assert!(!e.is_of(&d, &n, 7)); +} + /// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's /// pieces name swatches. #[test] @@ -1823,6 +1952,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() { } } +/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the +/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times. +fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { + if tops.contains(&top) { + break; + } + tops.push(top); + } + tops +} + +/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod +/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the +/// document, the group and its members, topmost first. +fn isolated_stack(count: u32) -> (Document, NodeId, Vec) { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); + let below = square(&mut d, 0.0); + d.insert(Some(l), usize::MAX, below).unwrap(); + let members: Vec = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect(); + let mut ids: Vec = members.iter().map(|n| n.id).collect(); + let g = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap(); + for x in [0.0, 100.0] { + let above = square(&mut d, x); + d.insert(Some(l), usize::MAX, above).unwrap(); + } + ids.reverse(); + (d, g, ids) +} + +/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above +/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where +/// only the art around the group lies. +#[test] +fn select_behind_in_isolation_lists_a_large_stack_once() { + let (d, g, ids) = isolated_stack(40); + let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope); + assert_eq!(at(47.5, Some(g)), ids); + assert_eq!(at(47.5, Some(g)).iter().collect::>().len(), 40, "no object twice"); + assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below"); + // At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within + // the tolerance): `ids[k]` is member 39 - k. + let left: Vec = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect(); + assert_eq!(left.len(), 20); + assert_eq!(at(17.5, Some(g)), left); + assert!(at(125.0, Some(g)).is_empty(), "only the square around the group"); + assert_eq!(at(125.0, None).len(), 1); + let isolated = HitOptions { scope: Some(g), ..HitOptions::default() }; + let p = Point::new(47.5, 25.0); + assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first"); + let (d, g, clip, art) = masked_square(false); + let isolated = HitOptions { scope: Some(g), ..SELECTING }; + for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] { + let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]); + assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}"); + } + assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides"); + assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline"); +} + +/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden +/// and locked objects), each object in turn isolated, and each list started with some of the +/// objects already found: the set lookup returns what the ordered-list lookup returns, field for +/// field. +#[test] +fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() { + let mut seed = 0x2545_f491_u32; + let mut next = move |n: u32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed % n + }; + fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) { + for _ in 0..2 + next(5) { + let id = d.alloc_id(); + let rect = |next: &mut dyn FnMut(u32) -> u32| { + let (x, y) = (f64::from(next(60)), f64::from(next(60))); + Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50))) + }; + let mut n = match next(if depth < 3 { 9 } else { 4 }) { + 4 | 5 => Node::group(id, Vec::new()), + 6 => { + let mut g = Node::group(id, Vec::new()); + g.set_clips(true); + g + } + 7 => { + let content = + (0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect(); + Node::new( + id, + NodeKind::Envelope { + content, + kind: Box::new(crate::live::EnvelopeKind::Warp { + style: "arc".to_string(), + bend: 0.0, + h: 0.0, + v: 0.0, + horizontal: true, + version: 0, + }), + fidelity: 100.0, + editing: next(2) == 0, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ) + } + _ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }), + }; + n.visible = next(8) != 0; + n.locked = next(8) == 0; + let group = matches!(n.kind, NodeKind::Group { .. }); + d.insert(Some(parent), usize::MAX, n).unwrap(); + if group { + fill(d, id, depth + 1, next); + } + } + } + let mut compared = 0; + for round in 0..60 { + let mut d = Document::new(120.0, 120.0); + let layer = d.layers[0].id; + fill(&mut d, layer, 0, &mut next); + let mut scopes = vec![None]; + d.walk(|n| { + if n.id != layer { + scopes.push(Some(n.id)); + } + }); + for _ in 0..6 { + let p = Point::new(f64::from(next(120)), f64::from(next(120))); + let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() }; + for &scope in &scopes { + let opt = HitOptions { scope, ..opt }; + let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]); + let context = format!("round {round}, {p:?}, {opt:?}"); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}"); + if scope.is_some() { + assert_eq!(objects_at(&d, p, opt, scope), want, "{context}"); + } + for found in 1..want.len() { + let start = want[..found].to_vec(); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found"); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found"); + } + compared += usize::from(!want.is_empty()); + } + } + } + assert!(compared > 500, "only {compared} non-empty lists compared"); +} + +/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup +/// against the ordered-list lookup, alternating the two in one process: +/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`. +#[test] +#[ignore = "a timing, not a check"] +fn select_behind_isolation_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + type Lookup = fn(&Document, Point, HitOptions, Option, Vec) -> Vec; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + let p = Point::new(47.5, 25.0); + for count in [200, 1_000] { + let (d, g, ids) = isolated_stack(count); + let opt = HitOptions { scope: Some(g), ..HitOptions::default() }; + assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids); + // The time per call of `f`: batches of calls double until one takes at least 100 ms. + let per_call = |f: Lookup| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![])); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 20 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(objects_at_repeated_after_by_list)); + new.push(per_call(objects_at_repeated_after)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, n) = (old[3], new[3]); + println!( + "{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs", + o.0 / 1e6, + o.1, + n.0 / 1e6, + n.1 + ); + } +} + /// Select Behind finds a symbol instance by its symbol's art, as a click does: art from /// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by /// one instance and 100 pt lower by an instance in a group. @@ -2397,7 +2736,7 @@ fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}"); assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}"); assert!(marquee(&d, past, None, false).is_empty()); - assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view"); + assert!(marquee_in_view(&d, edge, None, false, true, false).is_empty(), "Outline view"); } // Preview off for the layer the instance is on. let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false); diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index ed89f6ead4..149a8e488b 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -82,6 +82,16 @@ impl Paths { pub(crate) fn len(&self) -> usize { self.ids.len() } + /// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None` + /// when it isn't in the table. + pub(crate) fn entry(&self, id: &NodeId) -> Option> { + self.ids.get(id).copied() + } + /// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its + /// siblings. + pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> { + self.at.get(e as usize).copied() + } } /// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out) @@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() { TREE_WALKS.set(TREE_WALKS.get().saturating_add(1)); } +thread_local! { + /// [`path_lookups`] of this thread. + static PATH_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that +/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included. +pub fn path_lookups() -> u64 { + PATH_LOOKUPS.get() +} + +/// Adds one to [`path_lookups`]. +pub(crate) fn note_path_lookup() { + PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1)); +} + /// The cache, shared by clones of a document (each checks every path it uses against its own tree). #[derive(Default)] pub struct IdIndex(RwLock>>, std::sync::atomic::AtomicU32); diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index 86c26e14f4..b22f6cbfc7 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -117,6 +117,29 @@ impl Document { /// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot. /// Returns the ids of the texts in the layers that changed. pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec { + self.resolve_inline_art_since(None, layout).changed + } + + /// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved, + /// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the + /// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the + /// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then + /// still measures the same, the type in the layer trees that are the same nodes as `last`'s + /// already has these bounds: only the other layer trees are checked, in the same order, and + /// the document and the ids returned are those of the full pass. Otherwise, or without `last`, + /// the full pass runs. + pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass { + if let Some((last, kept)) = last + && self.same_inline_inputs(last, kept) + { + let measured = Measured(RefCell::new(kept.0.clone())); + let mut changed = vec![]; + let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed); + for (i, layer) in layers { + self.layers[i] = layer; + } + return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true }; + } let mut out = vec![]; let mut unused = vec![]; let graph = InlineGraph::of(self); @@ -147,10 +170,44 @@ impl Document { } } } - out + InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false } + } + + /// Whether the type in this document's layer trees that are the same nodes as `last`'s already + /// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]). + fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool { + self.symbols.len() == last.symbols.len() + && self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.graph_designs.len() == last.graph_designs.len() + && self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.patterns.len() == last.patterns.len() + && self + .patterns + .iter() + .zip(&last.patterns) + .all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y))) + && crate::Shared::ptr_eq(&self.unknown, &last.unknown) + && kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b) } } +/// What a pass of [`Document::resolve_inline_art_since`] did. +#[derive(Debug)] +pub struct InlinePass { + /// The ids of the texts in the layers that changed, in the order the full pass finds them. + pub changed: Vec, + /// The bounds the pass gave the inline graphics of each symbol name, for the next pass. + pub measured: InlineMeasured, + /// Whether only the layer trees that differ from the last resolved document's were checked. + pub partial: bool, +} + +/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each +/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the +/// pass before it measured, so the names of all the type in the document stay listed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct InlineMeasured(HashMap>); + /// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols. fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option) -> bool { t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol)) @@ -185,6 +242,22 @@ fn resolve_tree( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec, ) -> bool { + resolve_since(None, n, bounds, layout, changed) +} + +/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was +/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same +/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node +/// of the tree is visited. +fn resolve_since( + old: Option<&Node>, + n: &mut Arc, + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> bool { + #[cfg(test)] + tests::VISITS.with(|v| v.set(v.get() + 1)); let mut copied = false; if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) { let node = Arc::make_mut(n); @@ -196,17 +269,17 @@ fn resolve_tree( } copied = true; } + let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art); let mask = n.extras().mask.as_deref().and_then(|m| { - let mut art = m.art.clone(); - resolve_tree(&mut art, bounds, layout, changed).then_some(art) - }); - let mut kids = vec![]; - for (i, c) in n.children().into_iter().flatten().enumerate() { - let mut c = c.clone(); - if resolve_tree(&mut c, bounds, layout, changed) { - kids.push((i, c)); + if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) { + return None; } - } + let mut art = m.art.clone(); + let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o); + resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art) + }); + let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice)); + let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed); if mask.is_none() && kids.is_empty() { return copied; } @@ -224,6 +297,35 @@ fn resolve_tree( true } +/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list +/// before an edit) that has its id, found at the same position or else by id, and skips those that +/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new +/// node of each tree that changed. +fn resolve_kids( + old: Option<&[Arc]>, + kids: &[Arc], + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> Vec<(usize, Arc)> { + let mut by_id: Option>> = None; + let mut out = vec![]; + for (i, c) in kids.iter().enumerate() { + let o = old.and_then(|old| match old.get(i) { + Some(b) if b.id == c.id => Some(b), + _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), + }); + if o.is_some_and(|o| Arc::ptr_eq(o, c)) { + continue; + } + let mut c = c.clone(); + if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { + out.push((i, c)); + } + } + out +} + /// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`]. /// A symbol is first asked for after its own type is resolved (the pass goes in /// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass. @@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles { mod tests { use super::*; + thread_local! { + /// How many nodes [`resolve_since`] has visited on this thread. + pub(super) static VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// The nodes visited since the last call. + fn visits() -> usize { + VISITS.with(|v| v.replace(0)) + } + + /// A copy of `d` resolved by the full pass, and the ids that pass returns. + fn fully_resolved(d: &Document) -> (Document, Vec) { + let mut full = d.clone(); + let ids = full.resolve_inline_art_with(&mut |_| {}); + (full, ids) + } + + /// The children of the layer at `i`, for an edit. + fn layer_kids(d: &mut Document, i: usize) -> &mut Vec> { + match Arc::make_mut(&mut d.layers[i]).children_mut() { + Some(kids) => kids, + None => panic!("layer {i} is a group"), + } + } + + /// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing + /// `S` in the opacity mask of the second. + fn many_groups() -> Document { + let mut d = Document::new(500.0, 500.0); + let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)); + symbol(&mut d, "S", vec![square]); + for _ in 0..50 { + let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect(); + let group = Node::group(d.alloc_id(), kids); + d.layers.push(Arc::new(group)); + } + let t = showing(&mut d, "S"); + layer_kids(&mut d, 0).push(t); + let masked = showing(&mut d, "S"); + Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true))); + d + } + + #[test] + fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() { + let mut d = many_groups(); + let first = d.resolve_inline_art_since(None, &mut |_| {}); + assert!(!first.partial); + assert_eq!(first.changed.len(), 2); + let last = d.clone(); + visits(); + let _ = fully_resolved(&d); + let full_visits = visits(); + // The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the + // second group's opacity mask new type: its 20 squares stay the same nodes. + let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0)); + layer_kids(&mut d, 30)[5] = moved; + let added = showing(&mut d, "S"); + layer_kids(&mut d, 40).push(added.clone()); + let mask_type = showing(&mut d, "S"); + if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + m.art = mask_type.clone(); + } + let (want, ids) = fully_resolved(&d); + assert_eq!(ids, [mask_type.id, added.id]); + visits(); + let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {}); + let partial_visits = visits(); + assert!(pass.partial); + assert_eq!(pass.changed, ids); + assert_eq!(d, want); + // The three changed groups, the mask's new type, the moved square and the added type. + assert_eq!(partial_visits, 6); + assert!(full_visits > 1000, "{full_visits}"); + assert_eq!(pass.measured, first.measured); + } + + #[test] + fn changed_symbols_or_symbol_sizes_take_the_full_pass() { + let mut d = many_groups(); + let mut pass = d.resolve_inline_art_since(None, &mut |_| {}); + // A natural size for S, its art unchanged. + let last = d.clone(); + d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] })); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // New art for S. + let last = d.clone(); + let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0)); + d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger])); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // A measurement that no longer holds, with the same symbols and foreign data. + let last = d.clone(); + let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))])); + pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {}); + assert!(!pass.partial); + assert!(pass.changed.is_empty()); + } + /// The position of each node in `order`. fn positions(order: &[usize]) -> Vec { let mut at = vec![0; order.len()]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 18974db32a..fd1071711b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -17,11 +17,12 @@ pub mod corners; pub mod decode; pub mod depth; pub mod dimension; +pub mod flare; pub mod graph; mod halftone_radii; pub mod hit; mod id_index; -pub use id_index::tree_walks; +pub use id_index::{path_lookups, tree_walks}; pub mod inks; mod inline; pub mod intertwine; @@ -31,7 +32,7 @@ mod symbol_nine_slice; pub mod symbol_overrides; mod symbol_pixel_aligned; mod symbol_registration; -pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; +pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{ @@ -48,6 +49,8 @@ pub mod marks; mod mem; pub use mem::{appearance_heap_bytes, paint_heap_bytes}; pub mod metadata; +mod nearest; +pub use nearest::NearestFinder; pub mod node; pub mod objects_on_path; pub mod orient; @@ -168,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/live.rs b/crates/doc/src/live.rs index 28fd1dc632..337634db2e 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -66,7 +66,8 @@ pub use expand::{ use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; pub use warp::{ - WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version, + WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, + warp_point, warp_version, }; #[cfg(test)] diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index dd48e8ef65..a921c7d2ff 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -508,6 +508,17 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h)) } +/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position. +pub fn map_handles_within( + path: &PathData, + max_piece: f64, + max: usize, + f: impl Fn(Point) -> Point, + handle: impl Fn(Point, Point) -> Point, +) -> PathData { + map_pieces_within(path, max_piece, max, &f, handle) +} + /// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p` /// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve. fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { @@ -553,7 +564,8 @@ fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Po let c = seg_cubic(sp, i); let k = pieces(poly_len(&c), max_piece, MAX_PIECES); for j in 0..k { - let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)); + // Evaluating an unchanged curve can overflow even when its control points are finite. + let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) }; if let Some(last) = res.last_mut() { last.h_out = handle(sub.p0, sub.p1); } @@ -613,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec { } out } + +#[cfg(test)] +mod handle_tests { + use super::*; + + #[test] + fn an_unsplit_curve_keeps_its_finite_control_points() { + let start = Point::new(1e308, 0.0); + let end = Point::new(1.03e308, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)], + false, + )]); + assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path); + } + + #[test] + fn rounded_samples_preserve_a_smooth_interior_join() { + let center = Point::new(1e16, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![ + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)), + Anchor::with_handles( + center, + center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0), + center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0), + ), + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)), + ], + false, + )]); + let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1)); + let join = &mapped.subpaths[0].anchors[1]; + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + + #[test] + fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() { + for x in [1e16, 1e16 + 2.0, -1e16] { + for offset in [-6.0, -2.0, 2.0, 6.0] { + let p = Point::new(x, 0.0); + let h = Point::new(x + offset, 0.0); + assert_eq!(mapped_handle(&|point| point, p, h), h); + } + } + } +} 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/nearest.rs b/crates/doc/src/nearest.rs new file mode 100644 index 0000000000..0adc6269f9 --- /dev/null +++ b/crates/doc/src/nearest.rs @@ -0,0 +1,90 @@ +//! The nearest node of a kind at or above each of many objects, found along one index path per +//! object. + +use std::sync::Arc; + +use crate::id_index::Paths; +use crate::{Document, Node, NodeId}; + +/// Finds, for one object after another, the nearest node that passes a test: the object itself, +/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`]. +/// +/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that +/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache +/// places the object and each id on its path where they are, a lookup reads that one path; an id +/// the cache does not place there (one that appears more than once, or a cache older than the +/// tree) is looked up with [`Document::node`]. +pub struct NearestFinder<'a> { + doc: &'a Document, + cache: Option>, + /// The cache entries from the top-level layer down to the object. + entries: Vec, + /// The nodes at those entries. + nodes: Vec<&'a Node>, +} + +impl Document { + /// A [`NearestFinder`] for this document. + pub fn nearest_finder(&self) -> NearestFinder<'_> { + NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] } + } +} + +impl<'a> NearestFinder<'a> { + /// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred` + /// holds; `None` when `id` is not in the tree or no node on its path passes. + pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> { + let doc = self.doc; + let ids: Vec = if self.cached_path(id) { + let cache = self.cache.as_deref()?; + // The depth of the first id from the object up that the cache does not place there. + let mut unplaced = None; + for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() { + if cache.entry(&node.id) != Some(Some(e)) { + unplaced = Some(k); + break; + } + if pred(node) { + return Some(node); + } + } + let k = unplaced?; + self.nodes[..=k].iter().map(|n| n.id).collect() + } else { + doc.ancestry(id).unwrap_or_default() + }; + let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n))); + // Those lookups may have built the cache again. + self.cache = doc.index.get(); + found + } + + /// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for + /// it or the path no longer leads to it. + fn cached_path(&mut self, id: NodeId) -> bool { + self.entries.clear(); + self.nodes.clear(); + let Some(cache) = self.cache.as_deref() else { return false }; + let Some(Some(mut e)) = cache.entry(&id) else { return false }; + loop { + let Some((parent, _)) = cache.place(e) else { return false }; + self.entries.push(e); + if parent == u32::MAX { + break; + } + // A parent's entry is made before its children's, so the walk up ends. + if parent >= e { + return false; + } + e = parent; + } + self.entries.reverse(); + let mut siblings: &'a [Arc] = &self.doc.layers; + for &e in &self.entries { + let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false }; + self.nodes.push(&**n); + siblings = n.children().map_or(&[], |c| c.as_slice()); + } + self.nodes.last().is_some_and(|n| n.id == id) + } +} 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/live_shape.rs b/crates/doc/src/node/live_shape.rs index 9ddc4e1bb6..a384836442 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -179,6 +179,48 @@ impl LiveShape { *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; } } + /// A line's length in the document, from its first end to its second. None for other shapes. + pub fn line_length(&self) -> Option { + let LiveShape::Line { a, b } = self else { return None }; + Some((*b - *a).hypot()) + } + /// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the + /// direction from its first end to its second (the Rotate field's sense). 0 for a line whose + /// ends meet. None for other shapes. + pub fn line_angle(&self) -> Option { + let LiveShape::Line { a, b } = self else { return None }; + if a == b { + return Some(0.0); + } + // No −0° or 360° from rounding: a line drawn left to right reads 0°. + let a = (-self.angle_deg()).rem_euclid(360.0); + Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) + } + /// Make a line `len` long (0 or more), keeping its first end in place and its direction, or + /// pointing it to the right when its ends meet. + pub fn set_line_length(&mut self, len: f64) { + let LiveShape::Line { a, b } = self else { return }; + if !len.is_finite() || len < 0.0 { + return; + } + let now = (*b - *a).hypot(); + *b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) }; + } + /// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line + /// whose ends meet stays as it is. + pub fn set_line_angle(&mut self, angle: f64) { + let LiveShape::Line { a, b } = self else { return }; + let half = (*b - *a).hypot() / 2.0; + if !angle.is_finite() || half <= 0.0 { + return; + } + let mid = a.midpoint(*b); + let t = angle.to_radians(); + // The page's y axis points down, so a counterclockwise angle goes up the page. + let (dx, dy) = (half * t.cos(), -half * t.sin()); + *a = Point::new(mid.x - dx, mid.y - dy); + *b = Point::new(mid.x + dx, mid.y + dy); + } /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from /// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`]. pub fn make_sides_equal(&mut self) { diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index a616080bce..e83aae1b09 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -90,6 +90,42 @@ impl Node { matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. }) } + /// This object without the paths made into guides among the members of its groups, layers, + /// Intertwine groups and compound paths, at any depth, for measuring the art around them while + /// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or + /// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps + /// its structure. `None` when it holds no such guide. + pub fn without_guides(&self) -> Option { + let (NodeKind::Layer { children, .. } + | NodeKind::Group { children, .. } + | NodeKind::Intertwine { children } + | NodeKind::Compound { children, .. }) = &self.kind + else { + return None; + }; + let keep = usize::from(self.clips() || self.extras().shaper.is_some()); + let mut changed = false; + let mut out = Vec::with_capacity(children.len()); + for (i, c) in children.iter().enumerate() { + if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) { + changed = true; + } else if let Some(stripped) = c.without_guides() { + changed = true; + out.push(Arc::new(stripped)); + } else { + out.push(c.clone()); + } + } + if !changed { + return None; + } + let mut n = self.clone(); + if let Some(c) = n.children_mut() { + *c = out; + } + Some(n) + } + /// A template layer (Layer Options → Template). pub fn is_template(&self) -> bool { matches!(self.kind, NodeKind::Layer { template: true, .. }) @@ -216,8 +252,10 @@ impl Node { /// path give it ([`crate::hit::set_clip_region`]). An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their - /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box - /// takes in where its spine can put its keys and steps. + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the + /// shapes their art paints with the geometry effects of their own fill or stroke + /// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys + /// and steps. pub fn reach_bounds(&self) -> Option { self.reach(None) } @@ -254,14 +292,8 @@ impl Node { .map(|b| b.inflate(o, o)) } NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), - // The frame and each shape the image's own fills and strokes paint, a stroke's grown by - // the farthest it can reach from its shape. - NodeKind::Image(_) => { - crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| { - let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) - }) - } + // The frame and each shape the image's own fills and strokes paint. + NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols), // Keys and steps placed on a spine, turned to it with Align to Path, can reach past the // keys and the spine. NodeKind::Blend { children, spec } => { @@ -272,13 +304,15 @@ impl Node { NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => { vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c))) } - // The live geometry effects of the clipping paths in the art can draw it past its box. + // The live geometry effects of the clipping paths in the art can draw it past its box, + // and the box takes in each shape the art paints with the geometry effects of the + // instance's own fill or stroke. NodeKind::SymbolInstance { symbol, xf } => { let Some((s, art, region)) = symbols.and_then(|s| { let a = s.art(symbol)?; Some((s, a, a.reshaped?)) }) else { - return self.visual(symbols); + return self.with_own_paint(self.visual(symbols), symbols); }; let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf); let placed = if moves_only(*xf) && map.is_none() { @@ -294,12 +328,22 @@ impl Node { map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow) }; let o = self.appearance.outset(); - vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))) + self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols) } _ => self.visual(symbols), } } + /// `start` grown by each shape the node's own fills and strokes paint + /// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its + /// shape. + fn with_own_paint(&self, start: Option, symbols: Option<&SymbolBoxes>) -> Option { + crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| { + let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; + vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) + }) + } + /// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A /// symbol instance is measured as its transform applied to the 20 × 20 square around the origin /// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures @@ -476,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/setup.rs b/crates/doc/src/setup.rs index 4dd8394ce2..e91542fe1a 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option { LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q) } +/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the +/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written +/// as in an exported file. `None` for a language not in the list. +pub fn language_tag(language: &str) -> Option<&'static str> { + LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t) +} + /// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's /// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the /// first entry); `Err` for a language not in the list. @@ -404,6 +411,16 @@ impl DocSetup { mod tests { use super::*; + /// A document's language is written by its tag, the default's included (#3644). + #[test] + fn document_languages_have_their_tags() { + assert_eq!(language_tag(&DocSetup::default().language), Some("en-US")); + assert_eq!(language_tag("French"), Some("fr")); + assert_eq!(language_tag("german: swiss"), Some("de-CH")); + assert_eq!(language_tag("sr-latn"), Some("sr-Latn")); + assert_eq!((language_tag("Klingon"), language_tag("")), (None, None)); + } + /// Characters store a language of the list by its tag, the default as none. #[test] fn char_languages_are_stored_by_tag() { diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 9c25427846..0ee84dc32c 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -187,8 +187,9 @@ impl Document { /// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint /// visited once even when an id is inside another). pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize { + let listed: HashSet = ids.iter().copied().collect(); let roots: Vec = - ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect(); let mut n = 0; let mut g = relink(f); for id in roots { @@ -844,6 +845,77 @@ mod tests { assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + /// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set. + fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize { + let roots: Vec = + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + let mut n = 0; + let mut g = relink(f); + for id in roots { + let Some(node) = d.node(id) else { continue }; + if let Some((new, count)) = map_node(node, &mut g) + && let Some(slot) = d.node_mut(id) + { + *slot = new; + n += count; + } + } + n + } + + #[test] + fn mapping_within_ids_matches_a_search_of_the_ids() { + // Two layers: the first holds group `outer` (group `inner` with two rectangles, and a + // rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color. + let mut d = Document::new(100.0, 100.0); + let first = d.layers[0].id; + let second = d.alloc_id(); + d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap(); + let rect = |d: &mut Document, i: u8| { + let id = d.alloc_id(); + let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0); + (id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0)))) + }; + let (r1, n1) = rect(&mut d, 1); + let (r2, n2) = rect(&mut d, 2); + let (r3, n3) = rect(&mut d, 3); + let (r4, n4) = rect(&mut d, 4); + let (r5, n5) = rect(&mut d, 5); + let (inner, outer) = (d.alloc_id(), d.alloc_id()); + let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]); + d.insert(Some(first), usize::MAX, outer_node).unwrap(); + d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap(); + d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap(); + let missing = NodeId(u64::MAX); + let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing]; + // Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none. + let mut lists: Vec> = vec![vec![]]; + let mut shorter: Vec> = vec![vec![]]; + for _ in 0..3 { + shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect(); + lists.extend(shorter.iter().cloned()); + } + assert_eq!(lists.len(), 1 + 10 + 100 + 1000); + for ids in &lists { + // A callback that changes every paint it visits, so a paint visited twice counts twice. + let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| { + let mut d = d.clone(); + let mut visits = vec![]; + let n = map(&mut d, ids, &mut |c, s, t| { + visits.push((*c, s.clone(), *t)); + *s = Some(format!("{}", visits.len())); + *t *= 0.5; + true + }); + (n, visits, d.layers) + }; + let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f)); + let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f)); + assert_eq!(by_set, by_search, "{ids:?}"); + } + } + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { n.walk(&mut |m| { diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 2f83b65c5e..9c5c278a53 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() { } } +/// Every node whose id is in `ids`, by walking the tree. +fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> { + let mut out = vec![]; + d.walk(|n| { + if ids.contains(&n.id) { + out.push(n as *const Node); + } + }); + out +} + +/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids +/// included, with the cache built and without it, for a few ids (cached paths) and for many (a +/// walk). +#[test] +fn nodes_in_order_match_a_walk() { + for seed in 1..40 { + let (d, ids) = tree(seed); + let few: Vec = ids.iter().copied().step_by(17).collect(); + for cold in [true, false] { + if cold { + d.drop_lookup_cache(); + } else { + d.node(ids[0]); + } + for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] { + let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}"); + } + } + // An id that the tree repeats: every node with it. + let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue }; + assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once"); + // A second node given an id once held once, after the cache was built: the lookup finds the + // cached node, which has that id; with the cache built afresh, both. + let mut d = d; + let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer())); + let Some(once) = once else { continue }; + d.node(once); + let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, copy); + } + let found = d.nodes_in_order([once]); + assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}"); + d.drop_lookup_cache(); + d.node(once); + let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh"); + } +} + /// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each /// node it is in, appears in the tree once. fn picks(d: &Document, seed: u64) -> Vec { @@ -282,3 +334,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() { assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was"); } } + +/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node` +/// for each id finds it. +fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> { + d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node) +} + +/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone +/// each, so both start from the same cache. +fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) { + type Pred = fn(&Node) -> bool; + let preds: [(&str, Pred); 5] = [ + ("group", |n| matches!(n.kind, NodeKind::Group { .. })), + ("layer", |n| n.is_layer()), + ("any", |_| true), + ("none", |_| false), + ("id divisible by 3", |n| n.id.0 % 3 == 0), + ]; + for (name, pred) in preds { + let (a, b) = (d.clone(), d.clone()); + let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect(); + let mut find = b.nearest_finder(); + let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect(); + assert_eq!(got, want, "{what}: {name}"); + } +} + +#[test] +fn nearest_finder_matches_the_ancestry_walk() { + for seed in 1..30 { + let (mut d, ids) = tree(seed); + nearest_agrees(&d, &ids, "no cache"); + d.node(ids[0]); + nearest_agrees(&d, &ids, "cached"); + // Every path in the first layer shifts: the cache is stale there. + let extra = d.alloc_id(); + let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, leaf); + } + nearest_agrees(&d, &ids, "a stale cache"); + // A group with the id of a node in the last layer, earlier in tree order than it, put in + // after the cache was built. + d.drop_lookup_cache(); + d.node(ids[0]); + let last = d.layers.len() - 1; + let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id); + if let Some(dup) = dup + && let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() + { + ch.insert(0, Arc::new(Node::group(dup, vec![]))); + } + nearest_agrees(&d, &ids, "a duplicate put in after the cache was built"); + d.drop_lookup_cache(); + nearest_agrees(&d, &ids, "a duplicate, cached afresh"); + } +} + +/// An id on the path that an earlier node of another kind also has: the earlier node is the one +/// tested, as `node` gives it. +#[test] +fn nearest_finder_tests_the_first_node_with_a_repeated_id() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())); + d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap(); + d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap(); + // A group that has the path's id, after the path in tree order. + d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap(); + let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. }); + for cached in [false, true] { + d.drop_lookup_cache(); + if cached { + d.node(layer); + } + let mut find = d.nearest_finder(); + assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}"); + assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path"); + assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree"); + } +} + +/// With the cache built, finding the nearest group of every object of a large tree looks no id up +/// and walks the tree no time. +#[test] +fn nearest_finder_reads_one_path_per_object() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let mut leaves = vec![]; + for g in 0..2_000 { + let kids: Vec> = (0..3) + .map(|_| { + let id = d.alloc_id(); + leaves.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())) + }) + .collect(); + let gid = d.alloc_id(); + d.insert(Some(layer), g, Node::group(gid, kids)).unwrap(); + } + d.drop_lookup_cache(); + d.node(layer); + let (lookups, walks) = (path_lookups(), tree_walks()); + let mut find = d.nearest_finder(); + let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count(); + assert_eq!(found, leaves.len()); + assert_eq!(path_lookups() - lookups, 0, "lookups by id"); + assert_eq!(tree_walks() - walks, 0, "walks of the tree"); +} 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/bake.rs b/crates/effects/src/bake.rs index 274f9bdcc4..36418ac913 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; use crate::reshape::{ - as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves, + as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text, + paint_type_clip, reshape_leaves, }; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, @@ -502,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { { return None; } - let (bp, rule) = crate::clip_outline(first)?; - let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default()); - if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind { - (*r, *clipping) = (rule, true); - } - clip.name = first.name.clone(); - clip.visible = first.visible; + let clip = clip_region_path(first)?; let paint = first.clip_paint(); // The type's fills and strokes as art: baked with the type's id, as the renderer draws them, // then given ids of their own. @@ -532,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { return Some(m); }; // `n` keeps its id, name and transparency, and holds the clip group and the strokes over it. - let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + knockout_inside(&mut m, &mut inner); match &mut m.kind { NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => { *children = vec![Arc::new(inner), stroke]; diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index deb705752f..70bdc7731b 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let mut shadowed = type_node(55); shadowed.opacity = 0.5; shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); - // Type that clips a group is outlined as the plain outlines it clips by. + // Type that clips a group is outlined as a plain path of the region it clips by. let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true }); g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]); @@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let b = o.geometric_bounds().unwrap(); assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap(); - assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + // The region is copied with the type. + let b = clipped.geometric_bounds().unwrap(); + assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); } #[test] diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index ea727b804c..568aa583b1 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -189,7 +189,7 @@ pub fn effect_catalog() -> Vec { EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), ), g( @@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec { "{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}", json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}), ), - g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})), + g( + "distort.twist", + "Twist…", + DT, + "{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.", + json!({"angle": 10.0}), + ), g( "distort.zigZag", "Zig Zag…", diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 7a03a2f3aa..3fa1f3d152 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat use vectorcraft_pathops::addons::pathtools::insert_at; use crate::util::{ - catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, + catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, }; fn diag(b: Rect) -> f64 { @@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData { /// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle, /// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow -/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069). +/// the rotation's directional derivative, including each side of the outer circle. pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { let ang = angle.clamp(-3600.0, 3600.0).to_radians(); if ang == 0.0 { @@ -336,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { } let c = b.center(); let r = diag(b) / 2.0; + let half = Vec2::new(b.width() * 0.5, b.height() * 0.5); + let boundary = move |p: Point, length: f64| { + if length == r { + return true; + } + if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r { + return false; + } + // A bounds-relative distance identifies boundary points affected by center rounding. + (Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r + }; let f = move |q: Point| { let d = q - c; - let t = (1.0 - d.hypot() / r).max(0.0); + let length = d.hypot(); + let t = (1.0 - length / r).max(0.0); // y runs down, so a positive turn is clockwise on the page. let a = ang * t; + if a == 0.0 { + return q; + } let (s, co) = a.sin_cos(); c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) }; let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0)); - map_smooth_within(path, piece, max, f) + map_handles_within(path, piece, max, f, |p, h| { + let v = h - p; + if !v.hypot().is_finite() { + return f(p); + } + let d = p - c; + let length = d.hypot(); + let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 }; + // The clamped rotation has different inward and outward derivatives at the circle. + let inside = if boundary(p, length) { radial < 0.0 } else { length < r }; + let gradient = if inside { -ang / r * radial } else { 0.0 }; + let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient }; + let a = ang * (1.0 - length / r).max(0.0); + let (s, co) = a.sin_cos(); + f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co) + }) } const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4; 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 9531159e01..a6f5af916b 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S // Every path of the outline art, at any depth, is drawn inside the object's opacity // and blend mode. A symbol's art comes with the live objects and the instances of // other symbols inside it given as their art, and the type inside it outlined, so the - // art has nothing left for `hook` to give. + // art has nothing left for `hook` to give. Its fills and strokes carry the geometry + // effects of the instance's active fill and stroke, as the canvas draws them. if let Some(h) = hook && let Some(art) = h(n) { let art = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => { - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); + crate::reshape::add_instance_row_effects(doc, n, &mut art); crate::reshape::outline_nested_text(doc, &mut art, false); transparency_into_members(&mut art); art @@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S } } +/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and +/// the instances of other symbols inside it given as their art +/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry +/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]). +fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node { + let drawn = |m: &Node| { + let mut a = hook(m)?; + crate::reshape::add_instance_row_effects(doc, m, &mut a); + Some(a) + }; + crate::reshape::symbol_art_with(art, &drawn, nodes, symbol) +} + /// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is /// not Normal. fn within(l: &mut Node, n: &Node) { @@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod } }, // A symbol instance with a warp: its symbol's art placed by the instance, with the type - // inside it outlined, reshaped as one piece, as the renderer draws it. + // inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes + // of the art then carry the geometry effects of the instance's active fill and stroke. NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => { let h = hook?; let art = h(n).filter(|art| nodes.charge(art))?; - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); crate::reshape::outline_nested_text(doc, &mut art, false); members_as_drawn(doc, &mut art); + crate::reshape::add_instance_row_effects(doc, n, &mut art); let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); // The art's own fills and strokes follow the effects as its members do. if carry.moves(&art.appearance) { @@ -703,6 +720,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } } fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { + // A clip group whose clipping type's strokes paint around it is outlined as that clip + // group: the strokes outside the clip add nothing. + if let Some(inner) = crate::reshape::painted_clip_inner(n) { + return members(doc, inner, out); + } // A clip group shows its members only inside its clipping path: its outline is that // region, not the clipped members' own shapes, which may reach far outside it (#7289). if n.clips() { @@ -824,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); @@ -848,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 @@ -874,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) { @@ -883,15 +902,40 @@ 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 { - let shapes = member_shapes(doc, &m); - let bounds = m.geometric_bounds(); + // 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 + // that clip group. Such groups among the members are measured as their clip groups. + let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some(); + let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m)); let art = |items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() }; let (below, above) = m.appearance.split_contents(); let (below, above) = (art(below), art(above)); - let at = usize::from(m.clips()); - if let Some(ch) = m.children_mut() { + let at = usize::from(wrapped || m.clips()); + let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) }; + if let Some(ch) = target.and_then(Node::children_mut) { let at = at.min(ch.len()); ch.splice(at..at, below); ch.extend(above); @@ -905,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); @@ -929,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); @@ -962,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 9eae81118a..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, @@ -103,8 +105,8 @@ pub use solids::{ validate_three_d_params, view_options, with_graphic, }; pub use solids::{ - GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at, - graphics_reshaped_after, rename_appearance_graphic_symbol, + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, + graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; 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 50ecc6b549..85c36f2d89 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -387,7 +387,7 @@ fn row_effects_of(fx: &[Effect]) -> Vec { /// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its /// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no /// instance in the art takes them. -fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { +pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects)); let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects)); @@ -613,32 +613,101 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced { /// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`] /// makes along its frame or, for those whose first effect is Outline Object, along the outline of /// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the -/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches -/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and -/// the image's pixels in `doc` when the image does not hold them. +/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry +/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint +/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect +/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when +/// the image does not hold them. pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { - return vec![]; - } - let Some(art) = reshape(doc, n, None) else { return vec![] }; let mut out = vec![]; - art.walk(&mut |c| { - let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; - let Some(g) = c.stroke_path() else { return }; - let ctx = GeomContext { doc, ..GeomContext::of(c) }; - for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { - let fx = item.effects(); - let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { - crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) - } else { - g.clone() - }; - out.push((shape, *rule, item.clone())); - } - }); + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + let mut budget = SYMBOL_ART_MAX_NODES; + instance_paint(doc, n, 1, &mut budget, &mut out); + return out; + } + if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { + return out; + } + let Some(art) = reshape(doc, n, None) else { return out }; + art.walk(&mut |c| push_painted(doc, c, &mut out)); out } +/// The shapes that the fills and strokes of path or compound path `c` paint, each with the +/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects. +fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; + let Some(g) = c.stroke_path() else { return }; + let ctx = GeomContext { doc, ..GeomContext::of(c) }; + for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { + let fx = item.effects(); + let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { + crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + } else { + g.clone() + }; + out.push((shape, *rule, item.clone())); + } +} + +/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of +/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it, +/// each with its own geometry effects and those of each fill and stroke applied +/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of +/// the groups and layers in the art paint and the results of their Pathfinder effects +/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the +/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn. +/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of +/// Shaper groups add nothing, and neither does an instance more than +/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured +/// so far past `budget`. +fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) { + return; + } + let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return }; + let count = sym.art.count() as u64; + if count > *budget { + return; + } + *budget -= count; + let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return }; + painted_in(doc, &art, depth, budget, out); +} + +/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep. +fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) { + // One path for each fill and stroke, its effects applied. + Some(pieces) => painted_in(doc, &pieces, depth, budget, out), + None => push_painted(doc, n, out), + }, + NodeKind::Path { .. } => {} + NodeKind::Image(_) => out.extend(image_paint(doc, n)), + NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out), + _ if n.clips() => {} + _ => { + // A Pathfinder effect paints its result, not the members it combines. + let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten(); + let g = evaluated.as_ref().unwrap_or(n); + if g.clips() { + return; + } + // A Shaper group's first member holds its original shapes, which are not drawn. The + // group's own fills and strokes can be painted before it, so it is found by its id. + let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten(); + for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) { + painted_in(doc, c, depth, budget, out); + } + } + } +} + /// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one /// path per run, and all of them as one. pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath) { @@ -954,6 +1023,74 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option { Some(Node { visible: t.visible, ..o }) } +/// Clipping path `clip` of a clip group as a clipping path of the region it clips to +/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry +/// effects of its fills and strokes reshape what they paint and leave that region as it is. +/// `None` when it has nothing to clip by. +pub(crate) fn clip_region_path(clip: &Node) -> Option { + let (bp, rule) = crate::clip_outline(clip)?; + let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default()); + if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind { + (*r, *clipping) = (rule, true); + } + p.name = clip.name.clone(); + p.visible = clip.visible; + Some(p) +} + +/// Knockout Group for clip group `m` turned into a group around `inner`, a clip group of its +/// members, and its clipping path's strokes: `inner` takes `m`'s setting, so the clipped art knocks +/// out as before, and `m` is set Off so the strokes paint over it, as the renderer draws them. A +/// neutral `m` stays neutral, so both take the setting of the groups around them. +pub(crate) fn knockout_inside(m: &mut Node, inner: &mut Node) { + inner.knockout = m.knockout; + if m.knockout != vectorcraft_doc::Knockout::Neutral { + m.knockout = vectorcraft_doc::Knockout::Off; + } +} + +/// The clip group in `n` when `n` is a group or layer that [`paint_type_clip`] made of a clip +/// group and its clipping type's strokes: a group that does not clip whose first member is a clip +/// group with `n`'s id and whose second member has the id of that clip group's clipping path. The +/// clip group's region is what `n` stands for, as the clip group it was made from: the strokes +/// paint outside it and add nothing to its outline ([`crate::member_shapes`]) or its bounds +/// ([`clip_bounds`]). +pub(crate) fn painted_clip_inner(n: &Node) -> Option<&Node> { + if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let [inner, stroke, ..] = n.children()?.as_slice() else { return None }; + let clip = inner.children()?.first()?; + (inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner) +} + +/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that +/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type +/// outside the clip do not widen them. +pub(crate) fn clip_bounds(n: &Node) -> Option { + fn holds(n: &Node) -> bool { + painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c)) + } + fn unwrap(n: &mut Node) { + if let Some(inner) = painted_clip_inner(n) { + let mut inner = inner.clone(); + inner.visible = n.visible; + *n = inner; + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + unwrap(Arc::make_mut(c)); + } + } + } + if !holds(n) { + return n.geometric_bounds(); + } + let mut probe = n.clone(); + unwrap(&mut probe); + probe.geometric_bounds() +} + /// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look /// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes /// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and @@ -981,32 +1118,41 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping } /// When `n` is a clip group or clipping layer whose clipping path is type that paints -/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip -/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside -/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes -/// (keeping its id, name and transparency) with the clip group inside. The other members stay as -/// they are. Hidden type paints nothing. +/// ([`Node::clip_paint`]), make it the art the canvas draws for it: a path of the region the type +/// clips to clips ([`clip_region_path`]), its fills as art ([`as_art`]) paint behind the clipped +/// art inside the clip, and its strokes as art paint over it, outside the clip. Each part is the +/// type's art with only those fills or strokes, their own geometry effects applied. With strokes, +/// `n` becomes a group (keeping its id, name, visibility and transparency) that holds a clip group +/// of the clipping path, the fills and the other members, with `n`'s id, then the strokes; a +/// clipping layer keeps its ruler guides last. [`knockout_inside`] sets the Knockout Group of both, +/// and [`painted_clip_inner`] finds that clip group. The other members stay as they are. Hidden +/// type paints nothing. pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) { - let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return }; - if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible { + let Some(first) = n.children().and_then(|ch| ch.first()).filter(|_| n.clips()) else { return }; + if !matches!(first.kind, NodeKind::Text(_)) || !first.visible { return; } let paint = first.clip_paint(); if paint.fill.is_none() && paint.stroke.is_none() { return; } - let Some(clip) = clipping_text_outline(first) else { return }; + let Some(clip) = clip_region_path(first) else { return }; let art = |part: Option| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new); - let members: Vec> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect(); - let stroke = art(paint.stroke); + let (fill, stroke) = (art(paint.fill), art(paint.stroke)); let id = n.id; - match (&mut n.kind, stroke) { - (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members, - (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => { - *children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke]; - *clip = false; - } - _ => {} + let Some(ch) = n.children_mut() else { return }; + let Some(slot) = ch.first_mut() else { return }; + *slot = Arc::new(clip); + if let Some(fill) = fill { + ch.insert(1, fill); + } + let Some(stroke) = stroke else { return }; + let guides = ch.split_off(Node::guide_run_start(ch)); + let mut inner = Node::new(id, NodeKind::Group { children: std::mem::take(ch), clip: true }); + knockout_inside(n, &mut inner); + if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut n.kind { + *children = [Arc::new(inner), stroke].into_iter().chain(guides).collect(); + *clip = false; } } @@ -1822,7 +1968,7 @@ impl Step<'_> { if !groups.is_empty() { carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed)); } - let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art)); + let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art)); let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed)); Ran { kept: !kept_ids.is_empty(), took, masks, short, whole } } @@ -3247,6 +3393,9 @@ fn group_marks( NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false), NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => { let layer = matches!(n.kind, NodeKind::Layer { .. }); + // A clip group whose clipping type's strokes paint around it is measured as that clip + // group: the strokes outside the clip do not widen it ([`clip_bounds`]). + let clip = *clip || painted_clip_inner(n).is_some(); let skip = children.len().saturating_sub(n.editing_children().len()); let (mut bounds, mut held) = (None, false); for (i, c) in children.iter().enumerate() { @@ -3257,7 +3406,7 @@ fn group_marks( } at.pop(); // Only members measured in the bounds hold the group's gradients in place. - let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) }; + let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) }; if counts { bounds = vectorcraft_geom::union_opt(bounds, b); held |= h; @@ -3356,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); @@ -3473,16 +3622,17 @@ impl WarpedImages { /// The geometric bounds of `art` as it draws after the effects so far: each image this table /// lists measured by the pieces the warps and moves it took would cut it into, when the art - /// has room for them ([`cut_warped_images`]). + /// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip + /// are left out ([`clip_bounds`]). pub(crate) fn bounds(&self, art: &Node) -> Option { if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) { - return art.geometric_bounds(); + return clip_bounds(art); } // The pieces the images would be cut into now: each group of pieces is shown or hidden as // its image is, and hidden objects are left out of a layer's bounds. let mut probe = art.clone(); restore_warped_images(&mut probe, self, true); - probe.geometric_bounds() + clip_bounds(&probe) } /// The geometric bounds of image `n`: when this table lists it, measured by the pieces the diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index acd6cf7c94..43e60a0022 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -6,7 +6,7 @@ use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2}; -use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; +use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; use crate::solids::{ @@ -168,7 +168,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) // With no member to carry them, the graphics' art must still fit its limits. None => { crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; } } } @@ -201,10 +201,10 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op let graphics = crate::solids::mapped_graphics(p); let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) }; crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; let faces = vectorcraft_three_d::revolve(path, b, options)?; let mut used = *copies; - match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) { + match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), &mut used) { Some(_) => { *copies = used; Ok(()) @@ -523,7 +523,7 @@ fn surface( let mut parts = if graphics.is_empty() { vec![] } else { - match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) { + match crate::solids::graphics::surface_parts(doc, n.id, (&graphics, PlanarFace::Front), &faces, &shade, &mut used) { Some(parts) => { copies.graphics = used; parts diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index e21a88a26e..efe469e039 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -520,7 +520,8 @@ fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() { let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap(); let parts_of = |symbol: &str, copies: &mut usize| { let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]})); - crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len()) + crate::solids::graphics::surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), copies) + .map(|p| p.concat().len()) }; // Each opaque part copies the paint into its fill and its seam stroke; a part with // transparent stops takes no seam stroke and copies it once. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 2f8d0bf7bd..2bda4dc126 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -30,7 +30,7 @@ pub use graphics::{ }; pub use graphics::{ MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, - rename_appearance_graphic_symbol, + fitting as graphic_fitting_scale, rename_appearance_graphic_symbol, }; pub(crate) mod shadow; @@ -84,11 +84,14 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { } } // A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics - // on the back cap are dropped. + // on the back cap and on Extrude & Bevel's side are dropped. if (to == ROTATE || to == crate::REVOLVE) && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) { - list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id())); + list.retain(|g| { + let face = g.get("face").and_then(Value::as_str); + face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id()) + }); } Value::Object(out) } @@ -177,6 +180,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surface: false, } } @@ -253,6 +257,56 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> } } +/// [`facets`] of Extrude & Bevel with parameters `p`, with the pieces of the side of its longest +/// contour carrying where they lie on it unrolled ([`Facet::surface`]), for its side's graphics. +fn side_facets(path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result, String> { + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + vectorcraft_three_d::extrude(path, rule, bounds, Extrude { map_surface: true, ..extrude_options(p) }, view_options(p)) +} + +/// [`side_facets`], and with `cast` the faces the solid's shadow is cast from, from the same build +/// ([`facets_and_faces`]). +fn side_facets_and_faces(path: &PathData, rule: FillRule, bounds: Rect, p: &Value, cast: bool) -> Result { + if !cast { + return side_facets(path, rule, bounds, p).map(|f| (f, None)); + } + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + let options = Extrude { map_surface: true, ..extrude_options(p) }; + vectorcraft_three_d::extrude_shadowed(path, rule, bounds, options, view_options(p)).map(|(f, faces)| (f, Some(faces))) +} + +/// The part of `parts` ([`solid_parts`]) whose solid takes the graphics on Extrude & Bevel's side, +/// with parameters `p` and built about `bounds`: the first of those with the longest outline +/// ([`vectorcraft_three_d::extrude_side_size`]). `None` when the effect `id` is not Extrude & Bevel +/// or has no graphic on its side, or when no part has a side. +fn side_carrier(id: &str, p: &Value, parts: &[Part<'_>], bounds: Rect) -> Option { + if id != EXTRUDE || !mapped_graphics(p).iter().any(|g| g.face == PlanarFace::Side) { + return None; + } + let options = extrude_options(p); + parts + .iter() + .enumerate() + .filter_map(|(k, (_, _, area, rule, _, _))| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options).map(|(w, ..)| (k, w))) + .fold(None, |best: Option<(usize, f64)>, (k, w)| if best.is_some_and(|(_, top)| top >= w) { best } else { Some((k, w)) }) + .map(|(k, _)| k) +} + +/// The size of Extrude & Bevel's side unrolled for the graphics on it: the side of the part of +/// `shapes` that [`side_carrier`] picks, with parameters `p`, as wide as the part of it about x = 0 +/// that does not reach its cut and as tall as the length across its bevels and walls. +fn side_size(p: &Value, shapes: &[Profile]) -> Option<(f64, f64)> { + let (parts, bounds) = solid_parts(shapes, union_bounds(shapes)?); + let options = extrude_options(p); + parts + .iter() + .filter_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options)) + .fold(None, |best: Option<(f64, f64, f64)>, size| if best.is_some_and(|top| top.0 >= size.0) { best } else { Some(size) }) + .map(|(_, height, span)| (span, height)) +} + /// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast /// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the /// classic effects cast no shadow: they keep no faces. @@ -339,7 +393,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; check_profiles(id, p, &shapes, b)?; - return check_solids(id, p, &shapes); + check_solids(id, p, &shapes)?; + return check_side_graphics(doc, n, id, p, &shapes); } let (path, rule) = object_profile(n, label)?; let anchors = || format!("{label} requires a shape with at least two anchors"); @@ -356,7 +411,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let b = path.bounds().ok_or_else(anchors)?; let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; check_profiles(id, p, &shapes, b)?; - check_solids(id, p, &shapes) + check_solids(id, p, &shapes)?; + check_side_graphics(doc, n, id, p, &shapes) } /// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate @@ -370,6 +426,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool { paint_of(item, member).1 > 0.0 } +/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the +/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them +/// ([`side_carrier`]): their art, or the parts they draw on its pieces +/// ([`graphics::surface_parts`]), or when the object `n`'s surfaces can't be built at all. They are +/// built as the art builds them ([`surfaces_with`]), so its pieces are the ones the art draws, cuts +/// included. Without `doc` nothing is drawn, and nothing is checked. +fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { + let Some(doc) = doc else { return Ok(()) }; + let Some(b) = union_bounds(shapes) else { return Ok(()) }; + let (parts, bounds) = solid_parts(shapes, b); + if side_carrier(id, p, &parts, bounds).is_none() { + return Ok(()); + } + graphics::validate_surface_symbols(doc, p, PlanarFace::Side)?; + let fx = Effect { id: id.into(), params: p.clone(), visible: true }; + let mut dropped = false; + // Art that can't be built draws the source path, without the side's graphics. + let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped); + if dropped || built.is_none() { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + Ok(()) +} + /// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b` /// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate /// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is @@ -414,7 +494,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { if !cast { return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); } - let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true) + let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -688,6 +768,30 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by +/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]): +/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it +/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group. +fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { + if parts.iter().all(Vec::is_empty) { + return surface; + } + let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface }; + if children.len() != parts.len() { + return surface; + } + for (child, extra) in children.iter_mut().zip(parts) { + if extra.is_empty() { + continue; + } + let mut list = Vec::with_capacity(extra.len() + 1); + list.push(child.clone()); + list.extend(extra); + *child = Arc::new(Node::group(id, list)); + } + surface +} + /// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) @@ -802,7 +906,7 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { - built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f))) + built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f))) } /// One solid's facets and, when its shadow is cast, the faces it is cast from. @@ -813,7 +917,9 @@ type CastingSolid = (Vec, Option); type SurfacesAndFaces = (Vec>, Vec>); /// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow -/// is cast from, from the same build ([`SolidFaces`]). +/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one, +/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics +/// on Extrude & Bevel's side ([`side_carrier`]). fn built_solids_cast<'a>( id: &'a str, p: &'a Value, @@ -821,6 +927,7 @@ fn built_solids_cast<'a>( bounds: Rect, limit: usize, cast: bool, + side: Option, ) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. let mut inflated = (id == INFLATE).then(|| -> Box>> { @@ -834,7 +941,7 @@ fn built_solids_cast<'a>( }); let mut kept = 0usize; let mut ended = false; - parts.iter().map_while(move |(item, _, area, rule, _, _)| { + parts.iter().enumerate().map_while(move |(k, (item, _, area, rule, _, _))| { if ended { return None; } @@ -846,6 +953,7 @@ fn built_solids_cast<'a>( SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); each.next().unwrap_or_else(|| Ok((vec![], None))) } + None if side == Some(k) => side_facets_and_faces(area, *rule, bounds, p, cast), None => facets_and_faces(id, area, *rule, bounds, p, cast), }; let result = match built { @@ -1098,6 +1206,8 @@ fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Op f.depth = s.depth_at(mid).unwrap_or(s.depth); f.contours = vec![points]; f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign)); + // A piece keeps where the whole face lies on the side: the parts of the side's graphics + // drawn on it are cut to its own outline ([`graphics::SurfaceFace::curved`]). Some(f) }; Some((piece(1.0)?, piece(-1.0)?)) @@ -1776,6 +1886,12 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { /// solid built also keeps the faces its shadow is cast from, from the same build, in the order the /// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { + surfaces_with(doc, n, fx, shapes, cast, &mut false) +} + +/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past +/// their limits on the pieces drawn, and the solid that takes them draws without them. +fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -1818,9 +1934,13 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built)); } let (parts, bounds) = solid_parts(shapes, b); + // The graphics on Extrude & Bevel's side go once, on the side of the solid with the longest + // outline, whose pieces are built carrying where they lie on it. + let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None }; let mut solids = vec![]; let mut built = vec![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) { + let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier); + for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; match f { Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { @@ -1830,8 +1950,12 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile solids.push((item, *opacity, *scopes, f, *member)); built.push(faces); } - // A stroke's outline past the limits is left out; the fill's solid still draws. - Ok(None) => built.push(None), + // A stroke's outline past the limits is left out; the fill's solid still draws, and + // the side's graphics on that outline are not drawn. + Ok(None) => { + built.push(None); + *side_dropped |= carrier == Some(k); + } // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; // commands validate the same evaluator and report its errors. @@ -1915,6 +2039,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); let seal = |range: std::ops::Range| seals.get(range).is_some_and(|s| s.iter().any(|s| *s)); + let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default(); + // The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve. + let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { @@ -1922,10 +2049,22 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); + // The carrier's pieces draw the parts of the side's graphics that fall on them; past + // the graphics' limits the solid draws without them. + let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) { + vec![] + } else { + let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination)); + let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies); + *side_dropped |= parts.is_none(); + parts.unwrap_or_default() + }; + let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { - surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false)) + let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); + with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) }; (depths, art, scopes, ends) }) @@ -2239,8 +2378,18 @@ pub fn graphics_reshaped_after(n: &Node, item: Option, index: usize) -> b /// Finds a 3D effect in a list of effects, with its index there. type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p; -/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. -fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { +/// The size of the side unrolled of the Extrude & Bevel at `index` of the effects of `n` (on the +/// object itself with `item` `None`, else on its fill or stroke `item`), that a new graphic on it +/// fits: on the side of its solid with the longest outline, as wide as the part about x = 0 that +/// does not reach the side's cut, and as tall as the length across its bevels and walls. `None` when that effect is not a visible Extrude & Bevel with a +/// depth, or its art can't be built. +pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option<(f64, f64)> { + let (fx, shapes) = frame_shapes(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && e.id == EXTRUDE).map(|e| (index, e)))?; + side_size(&crate::merged_params(&fx.id, &fx.params), &shapes) +} + +/// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from. +fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option<(Effect, Vec)> { let n = &*resolve(doc, n, "").ok()?; let (fx, shapes) = if is_container(n) { let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; @@ -2264,6 +2413,12 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' } } }; + Some((fx.clone(), shapes)) +} + +/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. +fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { + let (fx, shapes) = frame_shapes(doc, n, item, pick)?; if !takes_graphics(&fx.id) { return None; } @@ -2289,10 +2444,19 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' let plane = vectorcraft_three_d::plane_face_map(b, view); return Some(graphics::GraphicFrame::new(b, plane, None)); } - let (_, bounds) = solid_parts(&shapes, b); + let (parts, bounds) = solid_parts(&shapes, b); let options = extrude_options(&p); let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face); - Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back))) + let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)); + // With graphics on the side, the part of it the viewer sees places their handles. + let side = side_carrier(&fx.id, &p, &parts, bounds) + .and_then(|k| parts.get(k)) + .and_then(|(_, _, area, rule, _, _)| side_facets(area, *rule, bounds, &p).ok()) + .map(|facets| graphics::SideFrame::of(&facets)); + Some(match side { + Some(side) => frame.with_side(side), + None => frame, + }) } /// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 7ef2fe4e28..bf4a71ace7 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -1,6 +1,6 @@ -//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials › -//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a -//! plane, turned, foreshortened and shaded with that face and clipped to it. +//! Graphics mapped onto a 3D object's faces (Window › 3D and Materials › Materials › +//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap or on its +//! side, or on a plane, turned, foreshortened and shaded with that face and clipped to it. //! //! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale, //! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of @@ -12,7 +12,10 @@ //! On Revolve the graphics lie on the swept side surface, unrolled flat //! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the //! middle of that surface, x around the axis and y along the profile, and each face of the side -//! draws the part of the graphics that falls on it ([`surface_parts`]). +//! draws the part of the graphics that falls on it ([`surface_parts`]). Graphics on Extrude & +//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the +//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with +//! the longest outline. use std::sync::Arc; @@ -110,7 +113,7 @@ impl MappedGraphic { }; let face = match m.get("face") { None => PlanarFace::Front, - Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?, + Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front, back or side"))?, }; let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result { match m.get(key) { @@ -139,7 +142,7 @@ impl MappedGraphic { * Affine::scale(self.scale / 100.0) * Affine::translate(-art.center().to_vec2()); match self.face { - PlanarFace::Front => place, + PlanarFace::Front | PlanarFace::Side => place, // Seen from behind, the back's right is the front's left. PlanarFace::Back => { Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place @@ -148,8 +151,8 @@ impl MappedGraphic { } } -/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve -/// (its swept side). +/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane) +/// and Revolve (its swept side). pub fn takes_graphics(id: &str) -> bool { id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE } @@ -165,7 +168,7 @@ pub fn mapped_graphics(p: &Value) -> Vec { /// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and /// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named -/// the front. +/// the front. Only Extrude & Bevel takes graphics on its side. pub fn validate(id: &str, p: &Value) -> Result<(), String> { let list = match p.get(GRAPHICS) { None => return Ok(()), @@ -183,10 +186,10 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { } for v in list { let g = MappedGraphic::from_value(v)?; - if id == super::ROTATE && g.face == PlanarFace::Back { + if id == super::ROTATE && g.face != PlanarFace::Front { return Err("A plane has one face: map its graphics onto the front".into()); } - if id == crate::REVOLVE && g.face == PlanarFace::Back { + if id == crate::REVOLVE && g.face != PlanarFace::Front { return Err("Revolve maps graphics onto its side: map them onto the front".into()); } } @@ -598,14 +601,14 @@ struct Unrolled { place: Affine, } -/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side -/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is -/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than -/// [`MAX_ELEMENTS`] points together. -fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option> { +/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side) +/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does +/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces +/// take more than [`MAX_ELEMENTS`] points together. +fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option> { let mut pieces = vec![]; let mut points = 0usize; - for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) { + for g in graphics.iter().filter(|g| g.face == face) { let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; let Ok(art) = pieces_of(doc, symbol) else { continue }; let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; @@ -682,38 +685,96 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option> (*points <= MAX_ELEMENTS).then_some(polygons) } -/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art, -/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together. -pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> { +/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit +/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface, +/// may take up to [`MAX_ELEMENTS`] points together. +pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> { let list = mapped_graphics(p); - if list.is_empty() || unrolled(doc, &list).is_some() { + if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() { return Ok(()); } Err("The graphics are too complex: simplify the symbols' art".into()) } -/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing -/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces -/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows -/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it. -/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the -/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol -/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past -/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`] -/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take -/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for -/// them: commands refuse such graphics, and a loaded file draws the surface without them. -pub(crate) fn surface_parts( +/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's +/// swept side, or a piece of Extrude & Bevel's walls and bevels. +pub(crate) trait SurfaceFace { + /// Where the face lies on the side unrolled, when it is a face of the side that shows its + /// outside to the viewer. + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>; + /// The outline the face's parts are cut to, when it is not the polygon of its cell's corners: + /// its curved outline, when its edges along an end are curved, or the outline of a piece cut + /// from a larger face. + fn curved(&self) -> Option>; + fn rgb_light(&self) -> Option; + fn light(&self) -> [f64; 3]; + fn outline_path(&self) -> PathData; +} + +impl SurfaceFace for vectorcraft_three_d::Face { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward && !self.cap) + } + fn curved(&self) -> Option> { + self.outline.as_ref().map(std::borrow::Cow::Borrowed) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + +impl SurfaceFace for Facet { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward) + } + fn curved(&self) -> Option> { + if let Some(outline) = &self.outline { + return Some(std::borrow::Cow::Borrowed(outline)); + } + // A piece of a stroke's face cut where it passes through a wall keeps its face's cell. + let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page)); + cut.then(|| std::borrow::Cow::Owned(self.path())) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + +/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side) +/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id +/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their +/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past +/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color +/// on a face, as the surface under it is shaded; the colors of gradients and patterns are +/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the +/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are +/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the +/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's +/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded +/// file draws the surface without them. +pub(crate) fn surface_parts( doc: Option<&Document>, id: NodeId, - graphics: &[MappedGraphic], - faces: &[vectorcraft_three_d::Face], - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + (graphics, face): (&[MappedGraphic], PlanarFace), + faces: &[F], + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, copies: &mut usize, ) -> Option>>> { let mut out: Vec>> = vec![vec![]; faces.len()]; let Some(doc) = doc else { return Some(out) }; - let pieces = unrolled(doc, graphics)?; + let pieces = unrolled(doc, graphics, face)?; let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) }; // Each piece listed in the buckets of the surface's x its bounds reach across. let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9); @@ -729,11 +790,12 @@ pub(crate) fn surface_parts( let mut cut_points = 0usize; let mut triangle_id = 0usize; for (face, parts) in faces.iter().zip(out.iter_mut()) { - let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue }; + let Some(cell) = face.outer_cell() else { continue }; if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { continue; } let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + let curved = face.curved(); for corners in triangles { triangle_id += 1; let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); @@ -744,7 +806,7 @@ pub(crate) fn surface_parts( // where the graphic runs past the end of the profile. A four-cornered face is cut into // two triangles along its diagonal from corner 0 to corner 2: each takes the part of // the outline on its own side of it. - let window = if face.outline.is_some() { grown(window, 3.0) } else { window }; + let window = if curved.is_some() { grown(window, 3.0) } else { window }; // The pieces are looked up over the whole of the window they are cut to. let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 { @@ -771,7 +833,7 @@ pub(crate) fn surface_parts( } near.sort_unstable(); let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2); - let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { + let rim = curved.as_deref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { (Some(&toward), Some(&a), Some(&b)) => { let side = side_of(a, b, toward); vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect) @@ -834,21 +896,21 @@ pub(crate) fn surface_parts( /// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes /// from the unrolled surface onto `face`. -fn surface_piece( +fn surface_piece( id: NodeId, piece: &Unrolled, (path, rule): (BezPath, FillRule), map: Affine, - face: &vectorcraft_three_d::Face, - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + face: &F, + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, ) -> Node { let gradient_map = map * piece.place; // Under several lights a face's light varies across it in each channel: a solid color draws // as the face's own lit art in that color, clipped to the part. An opaque part also draws that // art clipped to a band of the seam stroke's width around its edges, as the other parts take // a stroke over their seams. - if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) { - let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light)); + if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_light()) { + let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.outline_path(), &Paint::solid(c), light)); let clipped = |area: &BezPath, rule: FillRule| { let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default()); if let NodeKind::Path { rule: r, .. } = &mut clip.kind { @@ -881,7 +943,7 @@ fn surface_piece( match solid { Some(c) => f.paint = shade(face, c), None => { - vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination)); + vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.light())); } } } @@ -996,23 +1058,106 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option { } /// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics' -/// offsets are from their center) and the maps of its front and back faces, when it has them. -#[derive(Clone, Copy, Debug, PartialEq)] +/// offsets are from their center), the maps of its front and back faces, when it has them, and +/// the visible part of its side unrolled, when it has graphics there. +#[derive(Clone, Debug, PartialEq)] pub struct GraphicFrame { pub bounds: Rect, front: Option, back: Option, + side: Option, +} + +/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are +/// drawn on them ([`surface_parts`]): each piece's corners on the side unrolled and on the page, the +/// outline its parts are cut to when that is not the polygon of its corners, and its depth (larger +/// is nearer). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SideFrame { + pieces: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +struct SidePiece { + uv: Vec, + page: Vec, + outline: Option, + depth: f64, +} + +impl SideFrame { + /// The pieces of `facets` that carry where they lie on the side unrolled and show its outside. + pub(super) fn of(facets: &[Facet]) -> Self { + let pieces = facets + .iter() + .filter_map(|f| { + let cell = f.outer_cell().filter(|c| c.uv.len() == c.page.len() && (3..=4).contains(&c.uv.len()))?; + let outline = f.curved().map(|o| o.to_bezpath()); + Some(SidePiece { uv: cell.uv.clone(), page: cell.page.clone(), outline, depth: f.depth }) + }) + .collect(); + Self { pieces } + } + + /// Point `p` of the side unrolled mapped onto the page, or with `from_page` a page point mapped + /// onto the side unrolled, through the nearest piece whose drawn part holds it: within the + /// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and + /// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it. + fn map(&self, p: Point, from_page: bool) -> Option { + let inside = |t: &[Point; 3], q: Point| { + let side = |a: Point, b: Point| (b - a).cross(q - a); + let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; + s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) + }; + let mut best: Option<(Point, f64)> = None; + for piece in &self.pieces { + let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; + let triangles: &[[usize; 3]] = if from.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + for corners in triangles { + let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]); + let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue }; + let window = if piece.outline.is_some() { grown(a, 3.0) } else { a }; + if !inside(&window, p) { + continue; + } + // A four-cornered piece's two triangles meet along its diagonal: each holds its side. + if triangles.len() == 2 + && let (Some(&d0), Some(&d2), Some(&own)) = (from.first(), from.get(2), from.get(if corners[1] == 1 { 1 } else { 3 })) + { + let across = |q: Point| (d2 - d0).cross(q - d0); + if across(p) * across(own) < 0.0 { + continue; + } + } + let Some(q) = triangle_map(&a, &b).map(|m| m * p).filter(|q| q.is_finite()) else { continue }; + let on_page = if from_page { p } else { q }; + if piece.outline.as_ref().is_some_and(|o| !o.contains(on_page)) { + continue; + } + if best.is_none_or(|(_, depth)| piece.depth > depth) { + best = Some((q, piece.depth)); + } + } + } + best.map(|(q, _)| q) + } } impl GraphicFrame { pub(super) fn new(bounds: Rect, front: Option, back: Option) -> Self { - Self { bounds, front, back } + Self { bounds, front, back, side: None } + } + + /// The frame with the visible part of the side `side`, for its graphics' handles. + pub(super) fn with_side(self, side: SideFrame) -> Self { + Self { side: Some(side), ..self } } pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> { match face { PlanarFace::Front => self.front.as_ref(), PlanarFace::Back => self.back.as_ref(), + PlanarFace::Side => None, } } @@ -1023,23 +1168,34 @@ impl GraphicFrame { match face { PlanarFace::Front => Point::new(c.x + x, c.y + y), PlanarFace::Back => Point::new(c.x - x, c.y + y), + PlanarFace::Side => Point::new(x, y), } } /// Where graphic `g`'s center lands on the page, and whether its face is turned toward the - /// viewer. `None` when the object has no such face or the point has no page point. + /// viewer. `None` when the object has no such face or the point has no page point. A graphic on + /// the side lands where its center is on the part of the side the viewer sees, and is `None` + /// elsewhere. pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> { + if g.face == PlanarFace::Side { + return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true)); + } let map = self.map(g.face)?; Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible)) } - /// The offset of a graphic on `face` whose center lands on page point `page`. + /// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only + /// a point on the part of the side the viewer sees has one. pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { - let art = self.map(face)?.to_art(page)?; + let art = match face { + PlanarFace::Side => self.side.as_ref()?.map(page, true)?, + _ => self.map(face)?.to_art(page)?, + }; let c = self.bounds.center(); let (x, y) = match face { PlanarFace::Front => (art.x - c.x, art.y - c.y), PlanarFace::Back => (c.x - art.x, art.y - c.y), + PlanarFace::Side => (art.x, art.y), }; (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) } @@ -1047,11 +1203,17 @@ impl GraphicFrame { /// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most /// 100: where a newly mapped graphic starts. pub fn fitting_scale(&self, art: Rect) -> f64 { - let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9)); - (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) + fitting(self.bounds.width(), self.bounds.height(), art) } } +/// The scale (percent) at which art with bounds `art` fits inside a `width` × `height` area, at +/// most 100. +pub fn fitting(width: f64, height: f64, art: Rect) -> f64 { + let fit = (width / art.width().max(1e-9)).min(height / art.height().max(1e-9)); + (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) +} + /// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes'). pub fn graphic_symbols(n: &Node) -> Vec { appearance_graphic_symbols(&n.appearance) @@ -1135,3 +1297,7 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { #[cfg(test)] #[path = "tests_graphics.rs"] mod tests; + +#[cfg(test)] +#[path = "tests_graphics_side.rs"] +mod tests_side; diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 378299d514..b77903714e 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -774,6 +774,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { side: true, away: false, end: None, + surface: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index fe89dd1f84..92113017f9 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -531,12 +531,13 @@ fn graphics_are_checked() { let n = object(EXTRUDE, json!({})); let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics})); assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok()); + assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "side", "x": -40.0, "y": 5.0}])).is_ok()); assert!(check(EXTRUDE, json!([])).is_ok()); for bad in [ json!("Mark"), json!([{"face": "front"}]), json!([{"symbol": ""}]), - json!([{"symbol": "Mark", "face": "side"}]), + json!([{"symbol": "Mark", "face": "top"}]), json!([{"symbol": "Mark", "scale": 0.0}]), json!([{"symbol": "Mark", "rotation": 400.0}]), json!([{"symbol": "Mark", "x": "1"}]), @@ -546,10 +547,12 @@ fn graphics_are_checked() { assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}"); } assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); + assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err()); assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err()); // Revolve takes graphics on its side, named the front; Revolve (Classic) takes none. assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok()); assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err()); + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_err()); assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err()); // A loaded file's invalid entries are left out when drawn. assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1); @@ -569,10 +572,13 @@ fn the_frame_at_an_index_is_that_effects() { #[test] fn a_change_to_a_plane_drops_the_back_caps_graphics() { - let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]}); + let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}, {"symbol": "Mark", "face": "side"}]}); let plane = three_d_params_as(EXTRUDE, &p, ROTATE); assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}])); assert!(validate_three_d_params(ROTATE, &plane).is_ok()); + // Revolve drops the side's graphics too; Extrude & Bevel keeps every face's. + assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}])); + assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]); // Back to Extrude & Bevel, the front's graphic stays. assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]); } diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs new file mode 100644 index 0000000000..d216ff7d0d --- /dev/null +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -0,0 +1,255 @@ +//! Graphics on Extrude & Bevel's side: its walls and bevels unrolled flat. + +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{StrokeLayer, Symbol}; +use vectorcraft_geom::shapes; + +use super::super::{EXTRUDE, graphic_frame, graphic_side_size, solid_art_in, validate_three_d_in}; +use super::*; + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +fn square(id: u64, r: Rect, paint: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0)) +} + +/// A document with symbol "Mark": a red 10 × 10 square. +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { + dynamic: false, + name: "Mark".into(), + art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))), + }); + d +} + +/// A gray 100 × 100 square at (0, 0), extruded 50 pt, seen from above (its top wall faces the +/// viewer, its front edge at the bottom of the page), with `params` over that. +fn object(params: Value) -> Node { + let mut p = json!({"rotationX": -90.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) { + p.extend(extra.clone()); + } + let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + n +} + +fn is_red(p: &Paint) -> bool { + p.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1) +} + +/// The groups of a face and the parts of the side's graphics drawn on it, each part's outline. +fn faces_with_parts(art: &Node) -> Vec> { + let mut out = vec![]; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: false } = &n.kind + && let Some((face, parts)) = children.split_first() + && matches!(face.kind, NodeKind::Path { .. }) + && !parts.is_empty() + { + let red: Vec = parts + .iter() + .filter(|p| p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if is_red(&f.paint)))) + .filter_map(|p| p.path_data().cloned()) + .collect(); + if red.len() == parts.len() { + out.push(red); + } + } + }); + out +} + +fn bounds(parts: &[Vec]) -> Rect { + parts.iter().flatten().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6) +} + +/// x runs along the outline from the top's middle, clockwise as the front is seen, and y from the +/// middle of the side toward the back. +#[test] +fn a_side_graphic_lies_on_the_wall_at_its_offset() { + let d = document(); + let n = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let found = faces_with_parts(&art); + assert_eq!(found.len(), 1, "drawn once, on the top wall"); + // Seen from above, the top wall runs from its front edge (page y 75) to its back (page y 25). + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + let moved = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 20.0, "y": 10.0, "scale": 200.0}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &moved).unwrap()); + assert!(near(bounds(&found), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds(&found)); + // Without the document nothing is drawn; a graphic on the side leaves the caps without one. + assert!(faces_with_parts(&solid_art_in(None, &n).unwrap()).is_empty()); +} + +/// A graphic that reaches past a corner runs on around it onto the next wall. +#[test] +fn a_side_graphic_runs_around_a_corner() { + let d = document(); + // x = 50 is the top's right end. + let from_above = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &from_above).unwrap()); + assert!(near(bounds(&found), Rect::new(95.0, 45.0, 100.0, 55.0)), "only the top's part shows: {:?}", bounds(&found)); + // Turned to show the top and the right, both walls draw their part. + let turned = object(json!({"rotationX": -30.0, "rotationY": -40.0, "graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]})); + assert_eq!(faces_with_parts(&solid_art_in(Some(&d), &turned).unwrap()).len(), 2); + // Twist and taper carry the graphic; it stays on the side. + let twisted = + object(json!({"rotationX": -30.0, "rotationY": -40.0, "twist": 60.0, "taper": 50.0, "graphics": [{"symbol": "Mark", "face": "side"}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &twisted).unwrap()); + assert!(!found.is_empty() && found.iter().flatten().all(|p| p.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())))); +} + +/// The handle lands where the graphic's center is on the visible side, and a page point there +/// gives back its offset; a graphic on a hidden wall has no handle. +#[test] +fn the_sides_handle_moves_the_graphic_on_its_visible_part() { + let d = document(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 10.0, "y": -5.0})).unwrap(); + let n = object(json!({"graphics": [g.to_value()]})); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible && at.distance(Point::new(60.0, 55.0)) < 1e-6, "{at:?}"); + let (x, y) = frame.offset_at(PlanarFace::Side, Point::new(40.0, 45.0)).unwrap(); + assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); + // The bottom's middle, half way around, is hidden from above; so is a page point off the top. + let hidden = MappedGraphic { x: 200.0, ..g.clone() }; + assert!(frame.handle(&hidden).is_none()); + assert!(frame.offset_at(PlanarFace::Side, Point::new(50.0, 90.0)).is_none()); + // Without a graphic on the side, the frame places no handle there. + let caps = graphic_frame(Some(&d), &object(json!({"graphics": [{"symbol": "Mark"}]})), None).unwrap(); + assert!(caps.handle(&g).is_none()); +} + +/// On a curved wall, whose pieces are cut to its curved outline, the handle sits on the graphic's +/// center and a page point there gives back its offset. +#[test] +fn the_handle_follows_a_curved_side() { + let d = document(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 6.0, "y": 3.0})).unwrap(); + let mut n = object(json!({"rotationX": -60.0, "graphics": [g.to_value()]})); + if let NodeKind::Path { path, .. } = &mut n.kind { + *path = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + } + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible); + let (x, y) = frame.offset_at(PlanarFace::Side, at).unwrap(); + assert!((x - 6.0).abs() < 1e-6 && (y - 3.0).abs() < 1e-6, "{x} {y}"); +} + +/// A hollow object has no caps but takes graphics on its side; a stroke's solid, whose outline is +/// the longest, takes them once. +#[test] +fn a_hollow_or_stroked_object_takes_a_side_graphic() { + let d = document(); + let hollow = object(json!({"cap": false, "graphics": [{"symbol": "Mark", "face": "side"}, {"symbol": "Mark"}]})); + let art = solid_art_in(Some(&d), &hollow).unwrap(); + assert!(near(bounds(&faces_with_parts(&art)), Rect::new(45.0, 45.0, 55.0, 55.0))); + let mut stroked = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]})); + stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)), 10.0))); + let found = faces_with_parts(&solid_art_in(Some(&d), &stroked).unwrap()); + assert_eq!(found.len(), 1, "on the stroke's outer wall only"); + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + // The stroke's outer outline is 440 pt long, cut at a bottom corner 165 pt each way from the + // top's middle: a new graphic fits the 330 pt about x = 0 and the depth. + assert_eq!(graphic_side_size(Some(&d), &stroked, None, 0), Some((330.0, 50.0))); +} + +/// A stroke's face cut where it passes through a wall keeps the whole face's place on the side, and +/// each piece draws only the part of the graphic within its own outline. +#[test] +fn a_piece_cut_from_a_face_draws_its_own_part() { + let d = document(); + let facet = |x: f64, normal: [f64; 3], offset: f64| { + let square = vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let uv = square.iter().map(|p| Point::new(p.x - x, p.y)).collect(); + Facet { + contours: vec![square.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal, + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }), + plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + } + }; + let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); + // z = x - 8: behind the wall left of x = 8, in front of it right of it. + let r = std::f64::consts::FRAC_1_SQRT_2; + let mut stroke = vec![facet(5.0, [-r, 0.0, r], -8.0 * r)]; + super::super::cut_through(std::slice::from_ref(&wall), &mut stroke, &mut 10, &mut 0); + assert_eq!(stroke.len(), 2, "cut where it passes through the wall"); + // The graphic covers the whole face, x 5 to 15 on the page. + let graphics = mapped_graphics(&json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 5.0, "y": 5.0}]})); + let shade = |_: &Facet, c: Color| Paint::solid(c); + let parts = surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Side), &stroke, &shade, &mut 0).unwrap(); + let drawn: Vec = + parts.iter().map(|on| on.iter().filter_map(|n| n.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)).unwrap()).collect(); + // Each piece draws its own side of x = 8 (where the wall cuts it), together the whole graphic. + let (left, right) = (drawn[0].x0.min(drawn[1].x0), drawn[0].x1.max(drawn[1].x1)); + assert!((left - 5.0).abs() < 1e-6 && (right - 15.0).abs() < 1e-6, "{drawn:?}"); + assert!(drawn.iter().all(|b| (b.x0 - 8.0).abs() < 1e-6 || (b.x1 - 8.0).abs() < 1e-6), "{drawn:?}"); +} + +/// Commands refuse a side graphic whose curves, cut into straight pieces on the side, pass the +/// limit of points, though its own path elements are few; on a cap it is accepted. +#[test] +fn a_side_graphic_past_its_limits_is_refused() { + let mut d = document(); + // 200 circles 200,000 pt across: a few elements each, hundreds of thousands of points cut. + let mut subpaths = vec![]; + for k in 0..200 { + let x = f64::from(k); + subpaths.extend(shapes::ellipse(Rect::new(x, 0.0, x + 2e5, 2e5)).subpaths); + } + let rings = Node::path(NodeId(0), PathData::new(subpaths), Appearance::basic(Paint::solid(red()), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Rings".into(), art: Arc::new(rings) }); + let n = object(json!({})); + let side = json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings", "face": "side"}]}); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &side).is_err()); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings"}]})).is_ok()); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_ok()); +} + +/// With the shadow on, the solid that carries the side's graphics is built once, for both its faces +/// and its shadow: the graphic keeps its place on the wall, and the shadow is the one the object +/// casts without a graphic. +#[test] +fn a_side_graphic_keeps_its_place_with_the_shadow_on() { + let d = document(); + let shadow = |art: &Node| { + let first = &art.children().unwrap()[0]; + let [AppearanceItem::Fill(fill)] = first.appearance.items.as_slice() else { panic!("no shadow first: {first:?}") }; + assert!(fill.paint.color() == Some(Color::BLACK) && (fill.opacity - 0.5).abs() < 1e-6, "{fill:?}"); + first.path_data().and_then(PathData::bounds).unwrap() + }; + let lit = json!({"shade": true, "lightHeight": 90.0, "shadow": true, "shadowDistance": 50.0}); + let mut with_graphic = lit.clone(); + with_graphic["graphics"] = json!([{"symbol": "Mark", "face": "side"}]); + let n = object(with_graphic); + super::super::SOLID_GEOMETRY_BUILT.with(|b| b.set(0)); + super::super::SOLIDS_BUILT.with(|b| b.set(0)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let builds = (super::super::SOLID_GEOMETRY_BUILT.with(std::cell::Cell::get), super::super::SOLIDS_BUILT.with(std::cell::Cell::get)); + assert_eq!(builds, (1, 1), "one build for the faces and the shadow"); + let found = faces_with_parts(&art); + assert_eq!(found.len(), 1, "drawn once, on the top wall"); + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + let without = solid_art_in(Some(&d), &object(lit)).unwrap(); + assert!(near(shadow(&art), shadow(&without)), "{:?} {:?}", shadow(&art), shadow(&without)); +} diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 2d82d571c8..a2d8d03ad9 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() { let p = crate::merged_params(id, &json!({"shadow": true})); let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); let mut built: Vec> = - built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); + built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap(); assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}"); let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap(); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 52b38f986d..2a34fb1d07 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1708,6 +1708,115 @@ fn twist_joins_its_pieces_smoothly() { } } +#[test] +fn twist_boundary_handles_follow_the_inward_tangent() { + let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false)); + let bounds = Rect::new(40.0, 30.0, 60.0, 30.0); + for angle in [90.0_f64, 400.0, -720.0] { + let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds); + let anchors = &out.subpaths[0].anchors; + let start = anchors.first().unwrap(); + let end = anchors.last().unwrap(); + assert_eq!(start.p, Point::new(40.0, 30.0)); + assert_eq!(end.p, Point::new(60.0, 30.0)); + for (actual, expected) in [ + (start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())), + (end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())), + ] { + assert!(actual.hypot() > 1e-9); + let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs(); + assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees"); + } + } +} + +#[test] +fn twist_large_coordinate_joins_preserve_boundary_sides() { + use vectorcraft_geom::Anchor; + + let center = 1e16; + for offset in [32.0, 64.0] { + let p = Point::new(center + offset, 0.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 18.0, 0.0)), + Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)), + Anchor::corner(Point::new(p.x + 18.0, 0.0)), + ], + false, + )); + let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + if offset == 64.0 { + assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0)); + let actual = join.h_in - join.p; + let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "{actual:?}"); + } else { + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + } +} + +#[test] +fn twist_fractional_boundary_handles_use_each_sides_derivative() { + use vectorcraft_geom::Anchor; + + for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] { + for x in [bounds.x0, bounds.x1] { + for angle in [90.0_f64, 400.0, -720.0] { + let p = Point::new(x, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(x - 3.0 * step, 30.0)), + Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)), + Anchor::corner(Point::new(x + 3.0 * step, 30.0)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, angle, 3); + assert!( + out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()), + "x={x} angle={angle}: {:?}", + out.subpaths[0].anchors + ); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.distance(p) < 1e-10, "{:?}", join.p); + let a = angle.to_radians(); + let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] }; + for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) { + let expected = vectorcraft_geom::Vec2::new(dx, dy); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]); + } + } + } + } + let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0); + let center = bounds.center(); + let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false)); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + assert_eq!(out.subpaths[0].anchors[1].p, center); + let bounds = Rect::new(0.0, 30.0, 2e16, 30.0); + let p = Point::new(bounds.x1 - 8.0, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 12.0, p.y)), + Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)), + Anchor::corner(Point::new(p.x + 12.0, p.y)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.y - p.y > 10.0, "{:?}", join.p); + assert!(join.h_out.y - join.p.y < -4.0, "{join:?}"); +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 57566fbb28..d13c59f229 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -543,3 +543,337 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() { assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0)); } } + +fn blue() -> Paint { + Paint::solid(Color::rgb(0.0, 0.0, 1.0)) +} + +fn green() -> Paint { + Paint::solid(Color::rgb(0.0, 1.0, 0.0)) +} + +/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3 +/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and +/// stroked green 2 pt wide when `stroke`. +fn painted_type(id: u64, fill: bool, stroke: bool) -> Node { + use vectorcraft_doc::text::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + static FONT: std::sync::Once = std::sync::Once::new(); + FONT.call_once(|| { + vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds")); + }); + let style = CharStyle { + font_family: HEIGHT_FAMILY.into(), + size: 40.0, + fill: if fill { blue() } else { Paint::None }, + stroke: if stroke { green() } else { Paint::None }, + stroke_width: 2.0, + ..Default::default() + }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style)))) +} + +/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke? +fn paints(n: &Node, fill: bool) -> bool { + use vectorcraft_doc::AppearanceItem; + let own = n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => fill && f.paint == blue(), + AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0, + }); + own || n.children().into_iter().flatten().any(|c| paints(c, fill)) +} + +/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of +/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the +/// green stroke art right after the clip group (over it, outside the clip), and whether a green +/// stroke paints inside the clip group. +type Painted = (Rect, Option, Option, bool); + +fn painted_clip(n: &Node) -> Option { + let ch = n.children()?; + for (i, c) in ch.iter().enumerate() { + if let NodeKind::Group { children, clip: true } = &c.kind { + let region = clip_outline(children.first()?)?.0.bounding_box(); + let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds()); + let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds()); + let inside = children.iter().skip(1).any(|m| paints(m, false)); + return Some((region, fill, stroke, inside)); + } + if let Some(found) = painted_clip(c) { + return Some(found); + } + } + None +} + +fn near_rect(a: Rect, b: Rect) -> bool { + (a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5 +} + +#[test] +fn painted_clipping_type_survives_enclosing_geometry_effect() { + // Type that paints a fill, a stroke, both or neither clips a red square, in a group whose + // Transform (moving everything 10 pt down, beside other type that stays type in the export) or + // Offset Path reshapes its members: the canvas and the export keep the type's fill as art + // behind the square inside the clip and its stroke as art over the clip group, both reshaped + // with the clip. + let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box(); + assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}"); + let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))]; + for effect in effects { + for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] { + let clipped = clip_group(2, painted_type(3, fill, stroke)); + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]); + outer.appearance.effects.push(effect.clone()); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers.iter().find_map(|l| painted_clip(l)); + for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] { + let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id); + let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group")); + if effect.id == "distort.transform" { + assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}"); + } else { + let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0); + assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt"); + } + assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}"); + assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}"); + assert!(!inside, "{case}: the stroke paints outside the clip"); + for art in fills.into_iter().chain(strokes) { + assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}"); + } + } + } + } +} + +/// The group in `n` that holds a clip group and then the green stroke art of its clipping type, +/// with that clip group. +fn stroke_wrapper(n: &Node) -> Option<(&Node, &Node)> { + let ch = n.children()?; + if let [inner, stroke, ..] = ch.as_slice() + && matches!(inner.kind, NodeKind::Group { clip: true, .. }) + && !n.clips() + && paints(stroke, false) + { + return Some((n, inner)); + } + ch.iter().find_map(|c| stroke_wrapper(c)) +} + +#[test] +fn clipping_type_strokes_paint_over_a_knockout_clip_group() { + // A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its + // clipped art knocks out as the clip group says, and the type's stroke paints over it without + // knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's + // Transform around it, or by its own Offset Path. + use vectorcraft_doc::Knockout; + for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] { + for own in [false, true] { + let mut ty = painted_type(3, true, true); + if own { + ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1}))); + } + let mut clipped = clip_group(2, ty); + clipped.knockout = knockout; + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]); + if !own { + outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10}))); + } + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer.clone()).unwrap(); + let baked = bake_document(&d).unwrap(); + let canvas = if own { None } else { crate::evaluate_container(None, &outer) }; + let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l)); + for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] { + if own && what == "canvas" { + continue; + } + let case = format!("{what}, own effect {own}, knockout {knockout:?}"); + let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip")); + assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before"); + assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art"); + } + } + } +} + +#[test] +fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() { + // A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that + // strokes: the group's fill still paints inside the clip, and the type's stroke over it. + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let mut group = clip_group(2, painted_type(3, false, true)); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap(); + assert!(strokes.is_some() && !inside, "{canvas:?}"); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow)); + assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}"); + assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}"); +} + +#[test] +fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() { + // A clip group with an unplaced linear gradient fill of its own and an Offset Path effect, + // clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient + // spans the region the clipping path clips to. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let mut group = clip_group(2, ty); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box(); + let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }); + let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}"); +} + +#[test] +fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() { + // A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect + // (moving everything 10 pt down, or scaling it to half its width around its middle) holds a + // clip group clipped by type whose stroke has a Transform effect moving it 60 pt right, + // outside the clip. On the canvas and in the export, the clip region is the type's glyphs + // reshaped by the group's effect, and the group's fill paints that region alone, its gradient + // spanning it: the moved stroke adds nothing to the region, the fill or the box the group's + // effect scales around. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let live = clip_outline(&ty).expect("the type clips").0.bounding_box(); + let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0); + // Scaled to half its width around the middle of the clip, which the stroke does not move. + let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0); + let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1); + // The group's own fill art: every object outside the clip groups whose own fill is `paint`. + fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) { + let mine = n.appearance.items.iter().any(|i| match (i, paint) { + (vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)), + (vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p, + _ => false, + }); + if mine { + out.push(n); + } + for c in n.children().into_iter().flatten().filter(|c| !c.clips()) { + own_fills(c, paint, out); + } + } + let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)]; + for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) { + let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]); + outer.appearance = + Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group"); + for (what, art) in [("canvas", &canvas), ("export", &*exported)] { + let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" }); + let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}")); + assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}"); + let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art")); + assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}"); + let mut fills = vec![]; + own_fills(art, &paint, &mut fills); + assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}"); + let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}"); + if let Paint::Gradient(_) = paint { + for fill in fills { + let geom = match fill.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }; + let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!( + (left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, + "{case}: the gradient {geom:?} spans the clip {region:?}" + ); + } + } + } + } +} + +#[test] +fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() { + // A clip group with a placed linear gradient fill of its own, in a group with Free Distort, + // clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip: + // the gradient moves and scales from the clip's bounds, as for the same clip group whose type + // does not stroke. The moved stroke adds nothing to those bounds. + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp })); + fn placed_geom(n: &Node) -> Option { + if let Paint::Gradient(g) = n.appearance.fill_paint() + && g.geom.is_some() + { + return g.geom; + } + n.children().into_iter().flatten().find_map(|c| placed_geom(c)) + } + let ends = |stroke: bool| { + let mut ty = painted_type(3, false, false); + if stroke { + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + } + let mut group = clip_group(2, ty); + group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into(); + let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]); + let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}); + outer.appearance.effects.push(fx("distort.freeDistort", corners)); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + if stroke { + assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}"); + } + placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}")) + }; + let (plain, stroked) = (ends(false), ends(true)); + assert!( + plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5, + "the gradient {stroked:?} follows the clip as {plain:?} does" + ); +} diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs index de203b4955..6b79d19999 100644 --- a/crates/effects/src/util.rs +++ b/crates/effects/src/util.rs @@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { /// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of /// segments into pieces within an anchor budget. -pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces}; +pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces}; /// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight /// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 9f6ce7b710..a8209b9b42 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -59,6 +59,9 @@ chrono = { workspace = true } craft-xml = { workspace = true } # The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). cfb = "0.15" +# The Text Import Options character sets other than Unicode and ANSI (place/text.rs). Already in +# Cargo.lock (vectorcraft-eps), so this adds no new crate. +encoding_rs = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/engine/examples/layer_select_bench.rs b/crates/engine/examples/layer_select_bench.rs new file mode 100644 index 0000000000..256cada3af --- /dev/null +++ b/crates/engine/examples/layer_select_bench.rs @@ -0,0 +1,154 @@ +//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a +//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of +//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with +//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`, +//! the loop the command used before, copied here) and in one pass (`new`), side by side in one +//! process: first the whole command, then the selection step alone. Each case checks that both give +//! the same selection and reply before it is timed. +//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by +//! every run of `old` and of `new`. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(ms: &[f64]) -> f64 { + let mut ms = ms.to_vec(); + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares). +fn squares(n: usize) -> (Document, NodeId, Vec) { + let mut doc = Document::new(1600.0, 1200.0); + let layer = doc.layers[0].id; + let ids = (0..n) + .map(|i| { + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)]; + let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)); + let id = doc.alloc_id(); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap(); + id + }) + .collect(); + (doc, layer, ids) +} + +/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or +/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`]. +fn old_command(s: &mut Session, layer: NodeId) -> Value { + let st = s.doc().unwrap(); + let ids = st.doc.node(layer).unwrap().layer_art(true); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap(); + let st = s.doc_mut().unwrap(); + st.layer_rows = rows; + json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() }) +} + +fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) { + for i in ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } +} + +fn new_command(s: &mut Session, layer: NodeId) -> Value { + s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap() +} + +/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state. +fn time(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec, Vec) { + let run = |s: &mut S, f: &dyn Fn(&mut S)| { + let t = Instant::now(); + f(s); + t.elapsed().as_secs_f64() * 1000.0 + }; + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + let mut s = prepare(); + olds.push(run(&mut s, &old)); + black_box(&s); + let mut s = prepare(); + news.push(run(&mut s, &new)); + black_box(&s); + } + (olds, news) +} + +fn row(name: &str, (old, new): (Vec, Vec)) { + let (o, n) = (median(&old), median(&new)); + let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::>().join(" "); + println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9)); + println!(" old runs: {}", list(&old)); + println!(" new runs: {}", list(&new)); +} + +fn main() { + println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup"); + for n in [2_000usize, 20_000, 50_000] { + println!("{n} objects"); + let (doc, layer, ids) = squares(n); + let mut s = Session::new(); + s.add_document(doc, None); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut half = Selection::default(); + half.set(ids.iter().copied().step_by(2)); + for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] { + let reset = |s: &mut Session| { + let st = s.doc_mut().unwrap(); + st.selection = start.clone(); + st.layer_rows.clear(); + }; + // Both ways give the same selection and reply. + reset(&mut s); + let old_reply = old_command(&mut s, layer); + let old_sel = s.doc().unwrap().selection.clone(); + reset(&mut s); + let new_reply = new_command(&mut s, layer); + assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection"); + assert_eq!(new_reply, old_reply, "{name}: the same reply"); + + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] { + reset(&mut s); + let t = Instant::now(); + black_box(f(&mut s, layer)); + ms.push(t.elapsed().as_secs_f64() * 1000.0); + } + } + row(&format!("command, {name}"), (olds, news)); + // The selection step alone, on a copy of the starting selection. + let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true); + let selected: HashSet = start.objects.iter().copied().collect(); + let all_selected = art.iter().all(|i| selected.contains(i)); + let new_step = |sel: &mut Selection| { + if all_selected { + sel.remove_all(art.iter().copied()); + } else { + sel.add_all(art.iter().copied()); + } + }; + let (mut a, mut b) = (start.clone(), start.clone()); + old_step(&mut a, &art, all_selected); + new_step(&mut b); + assert_eq!(a, b, "{name}: the same selection step"); + row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step)); + } + } +} diff --git a/crates/engine/examples/link_colors_bench.rs b/crates/engine/examples/link_colors_bench.rs new file mode 100644 index 0000000000..d403339706 --- /dev/null +++ b/crates/engine/examples/link_colors_bench.rs @@ -0,0 +1,217 @@ +//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time +//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used +//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and +//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and +//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to. +//! For each it times two ways of finding the selected objects that no other selected object holds: a +//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids +//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both +//! give the same count, visit the same paints in the same order and leave the same document as +//! `map_solid_paints_in` before it times them. +//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10 +//! fresh copies of the document, and each row is the median time of one call. On Linux the times are the CPU time of the main thread, which runs +//! everything, in ms; elsewhere they are wall times. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::{HashMap, HashSet}; +use std::hint::black_box; +use std::sync::Arc; +use std::time::Instant; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Rect, shapes}; + +/// The colors the rectangles use, each with a swatch to link to. +const COLORS: usize = 50; + +/// The calls in each timed run; a row gives the time of one call. +const REPS: usize = 10; + +/// A way of finding the ids that no other listed id holds. +type Roots = fn(&Document, &[NodeId]) -> Vec; + +/// A way of applying a link function to the paints of the listed ids, returning the count changed. +type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only). +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise. +fn measure(f: impl FnOnce()) -> f64 { + match thread_cpu_ns() { + Some(start) => { + f(); + thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6) + } + None => { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + } + } +} + +/// Color `i` of [`COLORS`]: each has its own red value. +fn color(i: usize) -> Color { + Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25) +} + +/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models. +fn red_bits(c: &Color) -> u32 { + match c { + Color::Rgb { r, .. } => r.to_bits(), + _ => u32::MAX, + } +} + +/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor. +fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect() +} + +/// [`roots_by_search`] with each ancestor looked up in a set of the ids. +fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec { + let listed: HashSet = ids.iter().copied().collect(); + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect() +} + +/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed +/// paint put in place: the work of `map_solid_paints_in`. +fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize { + let mut n = 0; + for id in roots(d, ids) { + let Some(mut node) = d.node(id).cloned() else { continue }; + let count = map_node_solid_paints(&mut node, f); + if count > 0 + && let Some(slot) = d.node_mut(id) + { + *slot = node; + n += count; + } + } + n +} + +/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global +/// swatches, recording each paint visited. Returns the count and the visits. +fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option)>) { + let names: HashMap = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect(); + let mut visits = vec![]; + let n = map(d, ids, &mut |c, s, _| { + visits.push((*c, s.clone())); + match names.get(&red_bits(c)) { + Some(name) if s.is_none() => { + *s = Some(name.clone()); + true + } + _ => false, + } + }); + (n, visits) +} + +fn rect(d: &mut Document, i: usize) -> Arc { + let id = d.alloc_id(); + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0); + Arc::new(Node::path(id, r, a)) +} + +/// `n` rectangles in the first layer, all selected. +fn flat(n: usize) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for i in 0..n { + let node = rect(&mut d, i); + ids.push(node.id); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap(); + } + (d, ids) +} + +/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with +/// `groups` the two groups above each of them too, listed first. +fn nested(groups: bool) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let (mut outer_ids, mut leaves) = (vec![], vec![]); + for g in 0..1_000 { + let rects: Vec> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect(); + leaves.extend(rects.iter().map(|r| r.id)); + let inner = Node::group(d.alloc_id(), rects); + let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]); + if groups { + outer_ids.extend([outer.id, inner.id]); + } + d.insert(Some(l), usize::MAX, outer).unwrap(); + } + outer_ids.extend(leaves); + (d, outer_ids) +} + +fn bench(name: &str, (doc, ids): (Document, Vec)) { + let mut shipped = doc.clone(); + let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f)); + for roots in [roots_by_search as Roots, roots_by_set] { + let mut d = doc.clone(); + let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f)); + assert_eq!(got, want, "{name}: the same count and visits"); + assert_eq!(d.layers, shipped.layers, "{name}: the same document"); + } + let (mut old, mut new, mut real) = (vec![], vec![], vec![]); + let timed = |map: &mut Map| { + let mut docs = vec![doc.clone(); REPS]; + measure(|| { + for d in &mut docs { + black_box(link(d, black_box(&ids), &mut *map)); + } + }) / REPS as f64 + }; + for i in 0..iters() { + let run = |roots: Roots, out: &mut Vec| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f))); + if i % 2 == 0 { + run(roots_by_search, &mut old); + run(roots_by_set, &mut new); + } else { + run(roots_by_set, &mut new); + run(roots_by_search, &mut old); + } + real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f))); + } + let (old, new, real) = (median(old), median(new), median(real)); + println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new); +} + +fn main() { + let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" }; + println!( + " {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}", + "document", + "ids", + "linked", + format!("search, {unit}"), + format!("set, {unit}"), + format!("shipped, {unit}"), + "speedup" + ); + bench("2,000 rectangles in one layer", flat(2_000)); + bench("20,000 rectangles in one layer", flat(20_000)); + bench("5,000 rectangles in 1,000 groups of groups", nested(false)); + bench("the same with the 2,000 groups listed first", nested(true)); +} diff --git a/crates/engine/examples/stroke_targets_bench.rs b/crates/engine/examples/stroke_targets_bench.rs new file mode 100644 index 0000000000..b576968e49 --- /dev/null +++ b/crates/engine/examples/stroke_targets_bench.rs @@ -0,0 +1,146 @@ +//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set` +//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For +//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and +//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole +//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named. +//! The whole-command rows include the document copy the command makes for undo; each run is undone +//! before the next, outside the timed part. +//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere +//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each +//! row is the median in ms. A run of the two merge rows repeats the merge 1,000,000 / paths times +//! and gives the time of one. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read. +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise. +fn ms(f: impl FnOnce()) -> f64 { + let (cpu, wall) = (cpu_ns(), Instant::now()); + f(); + match (cpu, cpu_ns()) { + (Some(a), Some(b)) => (b - a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1000.0, + } +} + +fn median(mut v: Vec) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// `n` 10 pt squares in one group, and the squares' ids in stacking order. +fn document(n: usize) -> (Document, NodeId, Vec) { + let mut b = DocBuilder::new(4000.0, 4000.0); + let kids: Vec<_> = (0..n) + .map(|i| { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0); + b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6)) + }) + .collect(); + let leaves = kids.iter().map(|k| k.id).collect(); + let group = b.group(kids, false); + (b.build(), group, leaves) +} + +/// The merge that checks each leaf against the growing list. +fn listed(mut out: Vec, leaves: Vec) -> Vec { + for id in leaves { + if !out.contains(&id) { + out.push(id); + } + } + out +} + +/// The merge that checks each leaf against a set seeded with `out`. +fn with_set(mut out: Vec, leaves: Vec) -> Vec { + let mut seen: HashSet = out.iter().copied().collect(); + for id in leaves { + if seen.insert(id) { + out.push(id); + } + } + out +} + +fn row(name: &str, ms: f64) { + println!(" {name:<52} {ms:>10.3} ms"); +} + +/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part. +fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 { + let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::>(), "weight": 3}); + let runs = (0..iters()) + .map(|_| { + let mut r = Value::Null; + let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap())); + assert_eq!(r["objects"], n, "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + t + }) + .collect(); + median(runs) +} + +fn bench(n: usize) { + println!("{n} paths in one group"); + let (doc, group, leaves) = document(n); + + // Each run merges `reps` times, on copies made before the clock starts, and gives the time of one. + let reps = (1_000_000 / n).max(1); + let time = |f: fn(Vec, Vec) -> Vec| -> (f64, Vec) { + let mut last = Vec::new(); + let runs = (0..iters()) + .map(|_| { + let mut work: Vec> = (0..reps).map(|_| leaves.clone()).collect(); + let mut done = Vec::with_capacity(reps); + let t = ms(|| { + for input in &mut work { + done.push(f(Vec::new(), black_box(std::mem::take(input)))); + } + }); + last = done.pop().unwrap(); + t / reps as f64 + }) + .collect(); + (median(runs), last) + }; + let (old, a) = time(listed); + let (new, b) = time(with_set); + assert_eq!(a, b, "both merges give the same list"); + assert_eq!(a, leaves); + row("target merge, list search", old); + row("target merge, set", new); + println!(" {:<52} {:>10.1}x", "ratio", old / new); + + let mut s = Session::new(); + s.add_document(doc, None); + row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n)); + row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n)); +} + +fn main() { + println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" }); + for n in [2_000, 10_000, 20_000] { + bench(n); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index d41b1f7161..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; @@ -74,6 +75,7 @@ pub mod perspgrid; pub mod place; pub mod plugin; pub(crate) mod plugin_call; +mod preflight; pub mod prefscmds; pub mod print; pub(crate) mod printadvanced; @@ -98,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; @@ -321,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()); @@ -333,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()); @@ -382,6 +387,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(package::specs()); v.extend(slices::specs()); v.extend(print::specs()); + v.extend(preflight::specs()); v.extend(recovery::specs()); v.extend(fileio::dxfimport::specs()); v.extend(webexport::specs()); @@ -407,7 +413,18 @@ pub fn command_specs() -> &'static [CommandSpec] { /// The command `id`: a built-in one, or a command an installed plug-in adds /// ([`plugin::command_specs`]). pub fn find_command(id: &str) -> Option<&'static CommandSpec> { - command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id)) + static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id)) +} + +/// `specs` by id. An id that more than one spec has names the first of them, as a search of +/// `specs` in order finds. +pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> { + let mut index = std::collections::HashMap::with_capacity(specs.len()); + for spec in specs { + index.entry(spec.id).or_insert(spec); + } + index } /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in @@ -821,12 +838,16 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. +pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; -pub(crate) use edit::{settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; +/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. +pub use object::{reflect_axis, scale_factors, shear_tangent}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; @@ -859,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`). @@ -886,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.rs b/crates/engine/src/cmd/addons.rs index 7437abc0b5..03fb17f436 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,6 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub use packaging::{fold_source, print_hidden}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 6099386b98..9de16ca200 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -6,8 +6,10 @@ //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. mod check; +mod fold; mod roles; +pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; @@ -15,6 +17,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index da8f7f25dd..9507a17daa 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; -use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; +use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks}; use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; @@ -14,7 +14,7 @@ use crate::{Result, Session}; const CHECK: &str = "addon.packaging.check"; /// How far apart the ends of two lines may be and still be joined, in points. -const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); +pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); pub fn specs() -> Vec { vec![cmd!( @@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind { } } -fn check(s: &mut Session, p: &Value) -> Result { - let select = switch_or(p, "select", false, CHECK)?; - let tolerance = match length_given(p, "tolerance", CHECK)? { - None => TOLERANCE.1, - Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, - Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), - }; +/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or +/// `document`), the lines, and the ids of those on a non-printing layer. +pub(super) struct Lines { + pub scope: &'static str, + pub lines: Vec, + pub non_printing: Vec, +} + +/// The tolerance `p` gives for `cmd`, or the default. +pub(super) fn tolerance(p: &Value, cmd: &str) -> Result { + match length_given(p, "tolerance", cmd)? { + None => Ok(TOLERANCE.1), + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t), + Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + } +} + +/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while +/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines +/// are left out in every scope, members of a selected group included. +pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, CHECK)?; + let roots = checked_ids_or_selection(s, p, cmd)?; let d = &s.doc()?.doc; - // Hidden lines are left out in every scope, members of a selected group included. let shown = |ids: Vec| ids.into_iter().filter(|id| d.is_visible(*id)).collect::>(); - let (scope, targets) = match (given, roots.is_empty()) { - (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), - (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), - (false, true) => ("document", shown_targets(d)), - }; + Ok(match (given, roots.is_empty()) { + (true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)), + (false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)), + (false, true) => document_lines(d), + }) +} + +/// Every shown fold line of `d`. +pub(super) fn document_lines(d: &Document) -> Lines { + lines_of(d, "document", shown_targets(d)) +} + +fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { let table = RoleTable::of(d); let mut lines = vec![]; let mut non_printing = vec![]; @@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result { segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); lines.push(FoldLine { path, kind: kind(role), key: id.0 }); } - let (found, mut issues) = blanks(&lines, tolerance); - if !non_printing.is_empty() { - issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + Lines { scope, lines, non_printing } +} + +/// The blanks `lines` make and their issues, the non-printing one last. +pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec, Vec) { + let (found, mut issues) = blanks(&lines.lines, tolerance); + if !lines.non_printing.is_empty() { + issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None }); } - let ok = !issues.iter().any(|i| i.code.is_error()); - let rows: Vec = issues + (found, issues) +} + +/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with. +pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec { + issues .iter() .map(|i| { let mut row = json!({ @@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result { } row }) - .collect(); + .collect() +} + +fn check(s: &mut Session, p: &Value) -> Result { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = tolerance(p, CHECK)?; + let lines = lines(s, p, CHECK)?; + let scope = lines.scope; + let (found, issues) = found(&lines, tolerance); + let d = &s.doc()?.doc; + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows = issue_rows(&issues, scope); if select { let mut ids: Vec = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); ids.sort_unstable_by_key(|id| id.0); diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs new file mode 100644 index 0000000000..068b2375c9 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -0,0 +1,110 @@ +//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by +//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the +//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::{Blank, Issue, fold, pick}; + +use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or}; +use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance}; +use super::roles::{RoleTable, can_carry}; +use crate::{Result, Session}; + +const FOLD: &str = "addon.packaging.fold"; + +pub fn specs() -> Vec { + vec![cmd!( + query "addon.packaging.fold", + "Fold", + [], + None, + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + has_doc, + fold_command + )] +} + +/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the +/// whole document): what the Fold Preview window folds. +pub fn fold_source(d: &Document) -> (Vec, Vec) { + found(&document_lines(d), TOLERANCE.1) +} + +/// The objects the print on a folded blank leaves out: the layers that do not print and, unless +/// `fold_lines`, every object with a line role. +pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec { + fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec) { + match &n.kind { + NodeKind::Layer { printable: false, .. } => out.push(n.id), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)), + _ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id), + _ => {} + } + } + let table = RoleTable::of(d); + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out)); + out +} + +fn fold_command(s: &mut Session, p: &Value) -> Result { + let tolerance = tolerance(p, FOLD)?; + let amount = number_or(p, "amount", 1.0, FOLD)?; + if !(0.0..=1.0).contains(&amount) { + return Err(bad(FOLD, "`amount` must be from 0 to 1")); + } + let base = match p.get("base") { + None | Some(Value::Null) => None, + Some(v) => { + let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?; + Some(vectorcraft_geom::Point::new(x, y)) + } + }; + let lines = lines(s, p, FOLD)?; + let (blanks, issues) = found(&lines, tolerance); + let ok = !issues.iter().any(|i| i.code.is_error()); + let picked = pick(&blanks, base); + if base.is_some() && picked.is_none() { + return Err(bad(FOLD, "`base` is in no panel")); + } + let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?))); + let Some((index, blank, f)) = folded else { + return Ok(json!({ + "ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [], + "issues": issue_rows(&issues, lines.scope), + })); + }; + let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]); + let panels: Vec = blank + .panels + .iter() + .zip(&f.panels) + .map(|(panel, placed)| { + json!({ + "outline": panel.outline.to_bezpath().to_svg(), + "frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t}, + "parent": placed.parent, + "depth": placed.depth, + }) + }) + .collect(); + let hinges: Vec = f + .hinges + .iter() + .map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap})) + .collect(); + Ok(json!({ + "ok": ok, + "blank": index, + "blanks": blanks.len(), + "base": f.base, + "panels": panels, + "hinges": hinges, + "collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::>(), + "issues": issue_rows(&issues, lines.scope), + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/fold/tests.rs b/crates/engine/src/cmd/addons/packaging/fold/tests.rs new file mode 100644 index 0000000000..4c423021f5 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold/tests.rs @@ -0,0 +1,157 @@ +//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn fold(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.fold", &p).unwrap() +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only). +fn middle(d: &str) -> [f64; 2] { + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + let ((x0, x1), (y0, y1)) = (span(0), span(1)); + [(x0 + x1) / 2.0, (y0 + y1) / 2.0] +} + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn a_tray_folds_its_walls_up_round_the_base() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}"); + let panels = r["panels"].as_array().unwrap(); + assert_eq!(panels.len(), 5); + let base = r["base"].as_u64().unwrap() as usize; + let frame = &panels[base]["frame"]; + assert!( + near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]), + "{frame}" + ); + assert!(panels[base]["parent"].is_null()); + assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data"); + for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) { + assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}"); + // Each wall stands square to the base, below it (away from the print), its print facing out: + // away from the base's middle (190, 190), toward the side the wall lies on. + let [cx, cy] = middle(p["outline"].as_str().unwrap()); + let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"])); + let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy); + let (dx, dy) = (cx - 190.0, 190.0 - cy); + let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] }; + assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}"); + assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}"); + } + let hinges = r["hinges"].as_array().unwrap(); + assert_eq!(hinges.len(), 4); + assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}"); + assert_eq!(r["collisions"], json!([])); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step"); + + // Flat, every frame is the flat blank's own. + let r = fold(&mut s, json!({ "amount": 0 })); + for p in r["panels"].as_array().unwrap() { + assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}"); + } +} + +#[test] +fn the_base_is_the_panel_under_a_point() { + let mut s = session(); + tray(&mut s); + // The left wall: x 100 to 140, y 140 to 240. + let r = fold(&mut s, json!({ "base": [120, 190] })); + let base = r["base"].as_u64().unwrap() as usize; + let panels = r["panels"].as_array().unwrap(); + assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0])); + // The tray's base is now a child of the wall, and the other walls its children. + let depths: Vec = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect(); + let mut sorted = depths.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}"); + let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string(); + assert!(e.contains("`base` is in no panel"), "{e}"); +} + +#[test] +fn bad_values_are_refused() { + let mut s = session(); + tray(&mut s); + for (p, want) in [ + (json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"), + (json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"), + (json!({ "amount": "1" }), "`amount` must be a number"), + (json!({ "base": [1] }), "`base` must be a point"), + (json!({ "base": "middle" }), "`base` must be a point"), + (json!({ "tolerance": 50 }), "`tolerance` must be from"), + ] { + let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } +} + +#[test] +fn without_a_blank_nothing_is_folded_and_the_issues_say_why() { + let mut s = session(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}"); + assert_eq!(r["panels"], json!([])); + assert_eq!(r["issues"][0]["code"], "noCut"); +} + +#[test] +fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let art = path(&mut s, "M150 150 L200 150 L200 200 Z"); + let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let hidden: Vec = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect(); + for id in creases.iter().chain([&outline, ¬es]) { + assert!(hidden.contains(id), "{id} in {hidden:?}"); + } + assert!(!hidden.contains(&art)); + let shown: Vec = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect(); + assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out"); + let (blanks, issues) = cmd::fold_source(d); + assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5)); + assert!(issues.is_empty(), "{issues:?}"); +} diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 1c730e02b4..2d1ded312f 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,11 +3,13 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle +//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents +//! ([`tangents`]) and Tangent Circle //! ([`tangent_circle`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. +mod bridge; mod corners; #[cfg(test)] mod effect_tests; @@ -183,6 +185,7 @@ pub fn specs() -> Vec { v.extend(corners::specs()); v.extend(shared_edge::specs()); v.extend(trim::specs()); + v.extend(bridge::specs()); v.extend(tangent_circle::specs()); v.extend(tangents::specs()); v diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..4d4eb9cdf8 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -0,0 +1,164 @@ +//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both +//! 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}; +use vectorcraft_geom::PathData; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::super::super::pathops::{Beside, remove_each}; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or}; +use super::given; +use crate::{EngineError, Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command, and its undo step's name. +const C: &str = "addon.pathtools.bridge"; +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!( + "addon.pathtools.bridge", + "Smooth Bridge", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{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)?; + 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 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(); + d.paint_order(roots.iter().copied()) + .into_iter() + .filter_map(|id| match &d.node(id)?.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)), + _ => None, + }) + .collect() + }; + 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)) + } + }; + 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])?; + } + beside.finish(d)?; + } else { + // 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, &gone)?; + } + sel.set(made.iter().chain(&alone).copied()); + Ok(made) + })?; + 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 new file mode 100644 index 0000000000..745f216b68 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -0,0 +1,356 @@ +//! 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}; +use vectorcraft_geom::kurbo::Shape; + +use crate::Session; + +const BRIDGE: &str = "addon.pathtools.bridge"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// A circle about (`x`, `y`) with radius `r`. +fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId { + let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap(); + NodeId(id) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn top_level(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +fn area(s: &Session, id: NodeId) -> f64 { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(BRIDGE, &p).unwrap_err().to_string() +} + +#[test] +fn two_circles_become_one_outline_in_the_upper_ones_place() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + select(&mut s, &[a, b]); + 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") }; + assert!(live.is_none(), "a plain path now"); + assert!(path.subpaths.len() == 1 && path.subpaths[0].closed); + let bounds = path.bounds().unwrap(); + assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}"); + // Both circles and the bridge between them: more than the two circles' area. + assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), [a, b]); + assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was"); +} + +#[test] +fn keep_originals_adds_the_outline_above_the_upper_circle() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 30.0); + let b = circle(&mut s, 170.0, 100.0, 10.0); + let c = circle(&mut s, 300.0, 250.0, 5.0); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [a, b, id, c]); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle"); + assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are"); + assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. })); + let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap(); + assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); +} + +#[test] +fn a_kept_outline_gets_its_own_mask_art() { + 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 m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()); + s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap(); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id); + let (kept, copied) = (art(b).unwrap(), art(id).unwrap()); + assert_ne!(kept, copied, "the outline's mask art has ids of its own"); +} + +#[test] +fn a_larger_radius_makes_a_wider_bridge() { + let area_at = |radius: f64| { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 15.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + area(&s, id) + }; + let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0)); + assert!(default < wider && wider < widest, "{default} {wider} {widest}"); + let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0)); + assert!(narrow < default && default < wide, "{narrow} {default} {wide}"); + // The default is 100%: the smaller circle's radius. + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 15.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + assert!((area(&s, id) - default).abs() < 1e-9); +} + +#[test] +fn overlapping_and_touching_circles_are_joined() { + for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 140.0 + gap, 100.0, 20.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [id], "gap {gap}"); + } + // Unequal overlapping circles at every radius, the largest included. + for radius in [1.0, 100.0, 300.0, 1000.0] { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 125.0, 100.0, 30.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [id], "radius {radius}"); + } +} + +#[test] +fn far_apart_nested_and_other_objects_are_refused() { + let mut s = session(); + let a = circle(&mut s, 50.0, 100.0, 10.0); + let far = circle(&mut s, 250.0, 100.0, 10.0); + let near = circle(&mut s, 110.0, 100.0, 10.0); + let inner = circle(&mut s, 52.0, 100.0, 4.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let before = top_level(&s); + let steps = s.doc().unwrap().history.undo.len(); + // 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can. + assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius")); + assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok()); + s.execute("edit.undo", &json!({})).unwrap(); + // 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above + // ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested. + for radius in [100, 1000] { + let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius})); + 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, 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")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false")); + assert_eq!(top_level(&s), before); + 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(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + 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 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 or more circles to bridge")); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index 8102777687..e45e736109 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -1,7 +1,8 @@ //! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected //! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without //! crossing into either, added as separate open paths, with the line joining their centers if -//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. +//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it +//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. #[cfg(test)] mod tests; @@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", has_selection, common_tangents )] } -/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse, -/// else the path's one closed convex subpath. +/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact +/// ellipse for a whole live ellipse, else the path's one closed convex subpath. fn outline_of(d: &Document, id: NodeId) -> Result { const C: &str = COMMON_TANGENTS; let n = d.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) }; let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) }; + if sp.anchors.len() == 1 + && let Some(only) = sp.anchors.first() + { + return pt::Outline::point(only.p).map_err(refusal); + } if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() { let span = (pie.1 - pie.0).rem_euclid(360.0); if span < 1e-9 || 360.0 - span < 1e-9 { @@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { let ordered = d.paint_order(roots.iter().copied()); let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) }; let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?); + if a.is_point() && b.is_point() { + return Err(bad(C, "select two closed paths")); + } + // A point goes first, so that each line runs from it to where it touches the path. + let point = a.is_point() || b.is_point(); + let (a, b) = if b.is_point() { (b, a) } else { (a, b) }; let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?; let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count(); - let keep = |t: &&pt::Tangent| match kinds { - "external" => t.kind == pt::TangentKind::External, - "internal" => t.kind == pt::TangentKind::Internal, - _ => true, + // A point's external and internal tangents are the same lines: every kind keeps them. + let keep = |t: &&pt::Tangent| { + point + || match kinds { + "external" => t.kind == pt::TangentKind::External, + "internal" => t.kind == pt::TangentKind::Internal, + _ => true, + } }; let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect(); let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count(); - let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal)); + let (external_kept, internal_kept) = match (point, kinds) { + (true, "internal") => (0, kept.len()), + (true, _) => (kept.len(), 0), + _ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)), + }; let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + if lines.is_empty() && point { + // Written as `EngineError::Other` so that the i18n message scan finds it. + let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into()); + return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); + } if lines.is_empty() { // Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one // external tangent means one path lies inside the other and touches it there; paths that diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index aef694bbdd..7ab6b32838 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() { assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}"); } +fn point(s: &mut Session, x: f64, y: f64) -> NodeId { + id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap()) +} + +#[test] +fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() { + let mut s = session(); + // The point is drawn after the oval, so it is the upper object; the lines still start at it. + let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap()); + let dot = point(&mut s, 100.0, 200.0); + select(&mut s, &[oval, dot]); + let before = steps(&s); + let r = s.execute(C, &json!({"centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + assert_eq!(steps(&s), before + 1); + let found = lines(&s, &r); + assert_eq!(found.len(), 3, "two tangents and the centerline"); + let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0)); + // From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points + // are x = -a²/200 = -8, y = ±b √(1 - x²/a²). + let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt(); + for sy in [1.0, -1.0] { + let touch = c + Vec2::new(-8.0, sy * y); + assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}"); + } + assert_eq!(r["centerline"], r["ids"][2]); + assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]); + // Every `tangents` value gives the same two lines. + for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] { + let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}"); + assert_eq!(lines(&s, &r).len(), 2, "{kind}"); + } +} + +#[test] +fn a_point_below_the_path_still_starts_the_lines() { + let mut s = session(); + // The point is drawn first, so it is the lower object and needs no swap. + let dot = point(&mut s, 100.0, 200.0); + let round = circle(&mut s, 300.0, 200.0, 50.0); + let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + let found = lines(&s, &r); + assert_eq!(found.len(), 3, "two tangents and the centerline"); + let p = Point::new(100.0, 200.0); + assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}"); + // From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long. + let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt(); + assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}"); + assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]); +} + +#[test] +fn a_point_on_or_inside_a_path_and_two_points() { + let mut s = session(); + let round = circle(&mut s, 200.0, 200.0, 50.0); + // On the circle: one line, centered on the point and as long as the circle is wide. + let on = point(&mut s, 250.0, 200.0); + let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap(); + assert_eq!(r["external"].as_u64(), Some(1), "{r}"); + let (p, q) = lines(&s, &r)[0]; + assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}"); + // Inside: nothing changes, and the warning says why. + let inside = point(&mut s, 210.0, 190.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + // Two points, or a point and an open path, are refused. + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths")); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap()); + assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open")); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added"); +} + #[test] fn bad_selections_and_params_are_refused() { let mut s = session(); 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 34becd7c02..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}; @@ -172,6 +173,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons }, BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash }, BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, + BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive }, BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, @@ -179,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. @@ -232,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 { @@ -374,6 +425,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) } } +/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen +/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering. +fn pressure_sensitive() -> BrushLibrary { + let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin())); + let pulse = group(vec![ + black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())), + black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))), + ]); + let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush { + name: name.into(), + kind: BrushKind::Art(ArtBrush { + art, + width: light, + width_mode: Some(Variation::Pressure), + width_max: Some(heavy), + colorization: Colorization::Tints, + ..Default::default() + }), + }; + let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush { + name: name.into(), + kind: BrushKind::Calligraphic(Calligraphic { + angle, + roundness, + size, + variation: [0.0, 0.0, variation], + modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]), + }), + }; + built( + "Pressure Sensitive", + Document::new(100.0, 100.0), + vec![ + art_pressure("Flex Ribbon", flex, 35.0, 250.0), + art_pressure("Pulse Stroke", pulse, 45.0, 280.0), + nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0), + nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0), + ], + ) +} + /// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for /// blending and texture. fn bristle_brushes() -> BrushLibrary { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 57194d3d45..c026a1086e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -165,7 +165,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -211,7 +211,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), @@ -265,7 +265,7 @@ pub fn specs() -> Vec { "Redefine Symbol", [], None, - "{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", + "{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}", has_selection, symbol_update ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index c980f44adf..b0ab4366d2 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -32,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result { pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result { let name = name_param(p, "brush.get")?; let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?; - Ok(serde_json::to_value(b).unwrap_or_default()) + let mut v = serde_json::to_value(&b).unwrap_or_default(); + // A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way. + if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) { + o.entry("hue_jitter").or_insert(json!(sc.hue_jitter)); + } + Ok(v) } /// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]). diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index cecd314858..f5245bc9af 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); let pixel = pixel_grid_param(p, C)?.unwrap_or(false); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; + let iso = s.doc()?.isolation; // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { @@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); d.set_symbol_pixel_aligned(&name, pixel); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; Ok(json!({ "name": name, - "id": id.0, + "id": id.map(|i| i.0), "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), @@ -612,6 +622,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } // Redefining the symbol being edited leaves symbol editing mode in the same step. let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; if session.is_some() { crate::cmd::settle_interaction(s)?; s.end_text_edit(); @@ -625,10 +637,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } } let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; + // Nor can art that holds an instance of it, directly or through the symbols it nests. + if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) { + return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); + } crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); let (art, size, c) = normalize(art)?; let old = natural_size(&s.doc()?.doc, &name); let editing = session.is_some(); + // The isolation the kept art is selected in: the one from before symbol editing mode when + // the step leaves it. + let iso = match &session { + Some(se) => se.back_isolation, + None => s.doc()?.isolation, + }; let id = s.edit("Redefine Symbol", |d, sel| { if editing { crate::cmd::symboledit::finish(d, sel); @@ -647,15 +669,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } // Each instance keeps its appearance changes to the objects the new art still has. fit_overrides(d, &instances); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let reg = d.symbol_registration(&name); let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; if let Some(se) = &session { crate::cmd::symboledit::leave_editing(s, se)?; } - Ok(json!({ "name": name, "id": id.0 })) + Ok(json!({ "name": name, "id": id.map(|i| i.0) })) } /// How many levels of nested instances Delete Symbol expands before it gives up. 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/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 88c601b16b..18374f8302 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -121,7 +121,7 @@ pub fn specs() -> Vec { "Separations Preview", [], None, - "{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", + "{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", always, separations ), @@ -1055,6 +1055,13 @@ fn separations(s: &mut Session, p: &Value) -> Result { if let Some(n) = text_param(p, "only", C)? { v.separations = Some(vec![check(n)?]); } + // The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already + // shows alone among the active document's plates. + if let Some(n) = text_param(p, "soloToggle", C)? { + let n = check(n)?; + let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n])); + v.separations = Some(if alone { all.clone() } else { vec![n] }); + } if let Some(n) = text_param(p, "toggle", C)? { let n = check(n)?; let vis = v.separations.get_or_insert_with(|| all.clone()); 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 013b373d19..4bf123ea17 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -55,14 +55,23 @@ 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", "Circle Through Points", [], None, - "{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -126,7 +135,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -413,16 +422,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } -/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor -/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is. +/// A live ellipse whose edge passes through two or three points: `points`, or the two or three +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One +/// undo step, named as an Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { - Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?, - None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?, + Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; - let [a, b, c] = points; - let (center, radius) = shapes::circle_through(a, b, c) + let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; @@ -434,24 +443,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers. -fn three_points(v: &Value) -> Option<[Point; 3]> { +/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two +/// finite numbers. +fn two_or_three_points(v: &Value) -> Option> { let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), _ => None, }; - match v.as_array().map(Vec::as_slice) { - Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]), + match v.as_array() { + Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(), _ => None, } } -/// The positions of the selected anchor points, when there are exactly three. They are counted as +/// The positions of the selected anchor points, when there are two or three. They are counted as /// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with /// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own. /// A selected segment's ends are not selected anchor points, so a selection with segments gives /// none; so does a selection holding an object that is not a path, or an anchor that is gone. -fn selected_anchor_points(s: &Session) -> Result> { +fn selected_anchor_points(s: &Session) -> Result>> { let st = s.doc()?; if st.selection.segments.values().any(|set| !set.is_empty()) { return Ok(None); @@ -472,10 +482,7 @@ fn selected_anchor_points(s: &Session) -> Result> { return Ok(None); } } - Ok(match points.as_slice() { - &[a, b, c] => Some([a, b, c]), - _ => None, - }) + Ok(matches!(points.len(), 2 | 3).then_some(points)) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or @@ -517,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")?); @@ -942,7 +806,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result { let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); - if p.get("font").is_some() || p.get("style").is_some() { + // A face from a redefined [Normal Character Style] is checked too, as one given here is. + let normal_face = s + .doc() + .ok() + .and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR)) + .is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style")); + if p.get("font").is_some() || p.get("style").is_some() || normal_face { let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) { Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(), _ => Default::default(), @@ -970,8 +840,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle { /// The paragraph alignment, leading model and character alignment new type starts with (`t`'s /// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel` -/// and `charAlign` from `p`, else em box top to top and em box centre while the -/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a +/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that +/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432), +/// else the Roman baseline for both. Noted in the journal, so a /// replay sets the same whatever the interface. pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> { use vectorcraft_doc::{CharAlign, LeadingModel}; @@ -991,7 +862,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut l } }; - let align = match super::textedit::char_align_param(p, cmd)? { + // A redefined [Normal Character Style] that sets Character Alignment gives it to new type. + let normal_align = s + .doc() + .ok() + .and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR)) + .filter(|m| m.contains_key("charAlign")) + .and(t.runs.first().map(|r| r.style.char_align)); + let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) { Some(a) => a, None => { let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline }; @@ -1019,17 +897,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) } /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB -/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults, -/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill, -/// #7975), in the document's -/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error. +/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else +/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined; +/// never the current fill, #7975), in the style's language, else the document's. A `size` outside +/// [`super::typecmd::TYPE_SIZES`] is an error. pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result { - let mut style = CharStyle::default(); + let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc)); if let Some(sz) = p.get("size").and_then(Value::as_f64) { style.size = super::typecmd::given_type_size(sz, cmd)?; } + if str_param(p, "font").is_some() || str_param(p, "style").is_some() { + // A face given to the command takes its own version and axis settings, as a font change + // does, not those [Normal Character Style] gave another face. + style.font_version = None; + style.font_axes.clear(); + } if let Some(f) = str_param(p, "font") { style.font_family = f.to_string(); + // A family alone starts in Regular, whatever style [Normal Character Style] has. + style.font_style = CharStyle::default().font_style; } if let Some(f) = str_param(p, "style") { style.font_style = f.to_string(); @@ -1039,12 +925,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)), - None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)), + None => style.fill, }; - // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none - // for the default. Type already in a document keeps its own. - let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); - let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); - style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); + // In the language a redefined [Normal Character Style] gives, else the one Document Setup chose, + // else Preferences › Hyphenation › Default Language; none for the default. Type already in a + // document keeps its own. + if style.language.is_none() { + let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); + let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); + style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); + } Ok(style) } diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 183cbd3746..955401b923 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc}; use serde_json::{Value, json}; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::dimension::{ - ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition, -}; -use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition}; +use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2}; pub fn specs() -> Vec { @@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> LineType::Solid => None, }; if arrows { - let head = match o.arrow_style { - ArrowStyle::Filled => Some(Arrowhead::Triangle), - ArrowStyle::Open => Some(Arrowhead::TriangleOpen), - ArrowStyle::Tick => Some(Arrowhead::Slash), - ArrowStyle::None => None, - }; + let head = o.arrow_style.arrowhead(); st.start_arrow = head.clone(); st.end_arrow = head; st.arrow_scale = (o.arrow_scale, o.arrow_scale); diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 1e78f210e6..dc36e24380 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots}; use super::{ CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param, - named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, + named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req, }; use crate::EngineError; @@ -35,7 +35,7 @@ pub fn specs() -> Vec { "Width Point", [], None, - "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed", + "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed", has_doc, width_point_set ), @@ -214,6 +214,15 @@ fn uniform() -> WidthProfile { /// Width points closer than this (in t) are at the same place: a discontinuous point. const SAME_T: f64 = 1e-6; +/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a` +/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s +/// place. None when `a` is out of range or not such an incoming half. +pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option { + let t = points.get(a)?.0; + let at: Vec = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect(); + (at == [a, a + 1]).then_some(a + 1) +} + /// The stroke of `id` that width point commands edit (a compound path's for its members). fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> { let id = stroke_owner(d, id); @@ -265,9 +274,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below: } /// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest -/// points at other positions either side change in proportion (by the same amount from zero). -fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) { - let t = points[i].0; +/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after) +/// change in proportion (by the same amount from zero). +fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) { let scale = |v: f64, o: f64, n: f64| { let width = if o > 1e-9 { let product = v * n; @@ -284,8 +293,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6 }; width.max(0.0) }; - let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T); - let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T); + let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]); + let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]); for j in before.into_iter().chain(after) { let q = &mut points[j]; (q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2)); @@ -303,6 +312,46 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool { } } +/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to +/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With +/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point. +/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after +/// with the outgoing half, once each. → the index of the point (its incoming half). +fn set_pair( + points: &mut Vec<(f64, f64, f64)>, + (i, inc): (usize, (f64, f64, f64)), + (j, out): (usize, (f64, f64, f64)), + adjust: bool, + single: Option, +) -> Result { + const C: &str = "stroke.widthPoint.set"; + if width_point_pair(points, i) != Some(j) { + return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point")); + } + let at = points[i].0; + let (old_in, old_out) = (points[i], points[j]); + if (old_in.0 - inc.0).abs() > SAME_T { + return Err(bad(C, "a discontinuous width point keeps its place")); + } + let (new_in, new_out) = match single { + None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)), + Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)), + Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)), + }; + // Both halves measure their neighbors from the point's place, so a point within SAME_T of the + // outgoing half but not of that place is the point after the pair. + if adjust { + adjust_adjoining(points, i, at, old_in, new_in, [true, false]); + adjust_adjoining(points, j, at, old_out, new_out, [false, true]); + } + points[i] = new_in; + points[j] = new_out; + if single.is_some() { + points.remove(j); + } + Ok(i) +} + fn width_point_set(s: &mut Session, p: &Value) -> Result { const C: &str = "stroke.widthPoint.set"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -312,6 +361,25 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "left/right must be non-negative widths")); } let adjust = switch_or(p, "adjustAdjoining", false, C)?; + let single = match text_param(p, "single", C)? { + None => None, + Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"), + Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")), + }; + // The outgoing half of a discontinuous point: its index and side widths (points). + // `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`. + let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + let out = match p.get("outIndex") { + None | Some(Value::Null) if single.is_none() && !out_widths => None, + _ => { + let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?; + let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?); + if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 { + return Err(bad(C, "left/right must be non-negative widths")); + } + Some((j, l, r)) + } + }; // When the profile comes out as it was, within a rounding error (1e-9), the document and its undo // history stay as they are. let mut pos = 0; @@ -324,11 +392,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "width factors must be finite")); } let mut prof = st.profile.take().unwrap_or_else(uniform); - pos = match point_index(p, &prof, C)? { - Some(i) => { + pos = match (point_index(p, &prof, C)?, out) { + (None, Some(_)) => return Err(bad(C, "missing index")), + (Some(i), Some((j, l, r))) => { + let out = (t, l / half, r / half); + if !out.1.is_finite() || !out.2.is_finite() { + return Err(bad(C, "width factors must be finite")); + } + set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)? + } + (Some(i), None) => { let old = prof.points[i]; if adjust { - adjust_adjoining(&mut prof.points, i, old, pt); + adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]); } if (old.0 - t).abs() <= SAME_T { // Widths only: it keeps its place (and its side of a discontinuous point). @@ -339,12 +415,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { place(&mut prof.points, pt, old.0 < t) } } - None => { + (None, None) => { let old = adjust.then(|| prof.at(t)); prof.points.retain(|q| (q.0 - t).abs() > SAME_T); let i = place(&mut prof.points, pt, true); if let Some((left, right)) = old { - adjust_adjoining(&mut prof.points, i, (t, left, right), pt); + adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]); } i } diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 709b4cda65..717c9cdc14 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -238,7 +238,7 @@ pub fn specs() -> Vec { "Move Guide", [], None, - "{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies", + "{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies", guides_unlocked, guide_move ), @@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result { let dx = number_or(p, "dx", 0.0, "guide.move")?; let dy = number_or(p, "dy", 0.0, "guide.move")?; let copy = switch_or(p, "copy", false, "guide.move")?; + switch_or(p, "interpolate", false, "guide.move")?; if !s.doc()?.selection.is_empty() { let ids = super::edit::selected_roots(s)?; return super::object::apply_transform( diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e368473c4f..4e753ce00c 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", has_doc, freehand ), @@ -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/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 467bb091b3..607abf8f03 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -213,7 +213,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" }; let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; - if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { + let extend = p.get("extend").filter(|v| !v.is_null()); + if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "connect needs extend")); + } + if let Some(ext) = extend { let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?; let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) { None | Some(Some("end")) => false, @@ -238,26 +242,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s }; let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; *p0 = end; - if pts.len() < 2 { - // No stroke to add: the brush alone changes, when it is not the path's already, and the - // path is selected or deselected as a longer continuation leaves it. - if let Some(name) = brush_name - && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) - { - s.edit("Paintbrush", |d, sel| { - set_brush(d, target, name); - if keep_selected { - sel.set([id]); - } else { - sel.remove(id); - } - Ok(()) - })?; - } - return Ok(json!({ "id": id.0 })); - } // A stroke that ends on an open end of another path connects the two: (that path, its last // open subpath, that subpath starting at the end the stroke ends on, it ends at its end). + // It is checked before a stroke of one point returns, so a bad `connect` is refused there too. let connect = match p.get("connect").filter(|v| !v.is_null()) { Some(cn) => { let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?; @@ -280,6 +267,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s } None => None, }; + if pts.len() < 2 { + // No stroke to add: the brush alone changes, when it is not the path's already, and the + // path is selected or deselected as a longer continuation leaves it. + if let Some(name) = brush_name + && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) + { + s.edit("Paintbrush", |d, sel| { + set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } + Ok(()) + })?; + } + return Ok(json!({ "id": id.0 })); + } // `closed`, when given, says whether the stroke closes the path: the Pencil and the // Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release. // Left out, an extending stroke that ends within four Fidelities of the path's other end diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fbf5deb568..f126ac78ec 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit}; use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; use super::clipboard::SwatchChoices; use super::{ @@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { Ok(()) } +/// The document state that commands also change without an undo step: the perspective grid's view +/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its +/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each +/// undo and redo step keeps it as the document on its other side had it +/// ([`crate::HistoryEntry::unrecorded`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Unrecorded { + grid: vectorcraft_doc::GridPrefs, + export_settings: serde_json::Map, + brush: Option, + symbol: Option, + options: [bool; 5], + plane: Plane, +} + +impl Unrecorded { + pub(crate) fn of(d: &Document) -> Self { + let g = PerspectiveGrid::current(d); + Unrecorded { + grid: d.grid.clone(), + export_settings: d.export_settings.clone(), + brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(), + symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(), + options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers], + plane: g.plane, + } + } +} + +/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had +/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the +/// document before the undo or redo, since it changed after the step without an undo step. A part +/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also +/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the +/// active plane kept is not the one it holds. +fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc) { + fn pick(back: &T, step: &T, now: &T) -> T { + if back == step { now.clone() } else { back.clone() } + } + let back = Unrecorded::of(d); + let cur = Unrecorded::of(now); + let mut want = Unrecorded { + grid: pick(&back.grid, &step.grid, &cur.grid), + export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings), + brush: pick(&back.brush, &step.brush, &cur.brush), + symbol: pick(&back.symbol, &step.symbol, &cur.symbol), + options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])), + plane: pick(&back.plane, &step.plane, &cur.plane), + }; + if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) { + want.brush = back.brush.clone(); + } + if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) { + want.symbol = back.symbol.clone(); + } + if want == back { + return; + } + let m = Arc::make_mut(d); + for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] { + match v { + Some(v) => m.unknown.insert(key.into(), v.clone()), + None => m.unknown.remove(key), + }; + } + if (want.options, want.plane) != (back.options, back.plane) { + let mut g = PerspectiveGrid::current(m); + [g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options; + if g.plane != want.plane { + g.plane = want.plane; + g.inferred = None; + } + g.keep_positioning_valid(); + super::distortcmds::store_grid(m, &g); + } + m.grid = want.grid; + m.export_settings = want.export_settings; +} + fn undo(s: &mut Session, _: &Value) -> Result { settle_interaction(s)?; let menu = s.menu.clone(); @@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result { /// Select every surviving piece while retaining intentional compound-path structure. /// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths /// lose only the copied geometry. An exhausted partial path is removed, along with its compound -/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection -/// references with surviving object IDs. +/// parent if now empty; a compound left with one member stays a compound path, as after Clear; +/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which +/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on +/// success, replacing direct-selection references with surviving object IDs. fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { let st = s.doc()?; let sel = st.selection.clone(); @@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { // The selected ruler guides were copied too (#3226): they go in the same undo step. let gone = selection.guides.clone(); d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + // The compound paths that hold a root; one left with no members goes too. + let compounds: BTreeSet = roots + .iter() + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect(); let mut survivors = vec![]; let mut pieces = super::pathops::Beside::replacing(d, roots); for id in roots { let Some(node) = d.node(*id) else { continue }; let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); if !has_direct || node.path_data().is_none() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; continue; } let original = super::path::deletion_source(d, *id)?; @@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { } subpaths.retain(|sp| sp.anchors.len() >= 2); if subpaths.is_empty() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; } else { survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); } } pieces.finish(d)?; + let emptied: Vec = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect(); + super::pathops::remove_each(d, &emptied)?; selection.set(survivors); selection.anchors.clear(); selection.segments.clear(); @@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { ok() } -/// Remove object `id`, and the compound path that held it when it was the compound's last member. -/// A compound left with one member stays a compound path, as after Clear. -fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> { - let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); - d.remove(id)?; - if let Some(p) = parent - && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) - { - d.remove(p)?; - } - Ok(()) -} - fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; @@ -1533,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)?); } } @@ -1751,3 +1830,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn pub(crate) fn arc_nodes(v: Vec) -> Vec> { v.into_iter().map(Arc::new).collect() } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs new file mode 100644 index 0000000000..8146bec6c2 --- /dev/null +++ b/crates/engine/src/cmd/edit/tests.rs @@ -0,0 +1,343 @@ +//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties +//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection, +//! the clipboard and the undo history exactly as removing each of them on its own does. + +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks}; + +use super::*; +use crate::tests_large_edits::{session, square}; + +/// Cut's removal with every root selected whole or emptied taken out by its own +/// [`Document::remove`], and its compound path removed right after when that left it empty. The +/// tests compare [`cut_direct_selection`] with it. +fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result { + let st = s.doc()?; + let sel = st.selection.clone(); + s.edit("Cut", |d, selection| { + let gone = selection.guides.clone(); + d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + let mut survivors = vec![]; + let mut pieces = super::super::pathops::Beside::replacing(d, roots); + for id in roots { + let Some(node) = d.node(*id) else { continue }; + let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); + if !has_direct || node.path_data().is_none() { + remove_one(d, *id)?; + continue; + } + let original = super::super::path::deletion_source(d, *id)?; + let seg_refs = sel.segments.get(id); + let anchor_refs = sel.anchors.get(id); + let mut subpaths = Vec::new(); + let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths); + for (si, sp) in owned.into_iter().enumerate() { + let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs); + if cuts.is_empty() { + subpaths.push(sp); + } else if seg_refs.is_some_and(|segments| !segments.is_empty()) { + subpaths.extend(super::super::path::without_segments(sp, &cuts)); + } else { + let gone: BTreeSet = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect(); + subpaths.extend(super::super::path::without_anchors(sp, &gone)); + } + } + subpaths.retain(|sp| sp.anchors.len() >= 2); + if subpaths.is_empty() { + remove_one(d, *id)?; + } else { + survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); + } + } + pieces.finish(d)?; + selection.set(survivors); + selection.anchors.clear(); + selection.segments.clear(); + Ok(()) + })?; + ok() +} + +/// Removes object `id`, and the compound path that held it when it was the compound's last member. +fn remove_one(d: &mut Document, id: NodeId) -> Result<()> { + let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + d.remove(id)?; + if let Some(p) = parent + && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) + { + d.remove(p)?; + } + Ok(()) +} + +/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of +/// [`cut_direct_selection`]. +fn reference_cut(s: &mut Session) { + let (direct, roots) = copy_cut_targets(s).unwrap(); + assert!(direct, "the selection is a direct selection"); + copy(s, &json!({})).unwrap(); + cut_one_at_a_time(s, &roots).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`. +fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) { + run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::>()})); + for (id, anchors) in partial { + run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"})); + } +} + +/// The ids of every node of the document, depth first, with the depth of each. +fn tree(d: &Document) -> Vec<(usize, NodeId)> { + fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) { + out.push((depth, n.id)); + for c in n.children().into_iter().flatten() { + walk(c, depth + 1, out); + } + } + let mut out = vec![]; + for l in &d.layers { + walk(l, 0, &mut out); + } + out +} + +/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo +/// steps. +fn assert_same(a: &Session, b: &Session, when: &str) { + let (x, y) = (a.doc().unwrap(), b.doc().unwrap()); + assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree"); + assert!(*x.doc == *y.doc, "{when}: the document"); + assert_eq!(x.selection, y.selection, "{when}: the selection"); + // Each session's document has its own uid; the clipboard names the one it came from. + assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source"); + let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() }; + assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard"); + assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps"); + assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps"); +} + +/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks +/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after +/// the Cut. +fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session { + let (mut a, mut b) = (make(), make()); + let before = a.doc().unwrap().doc.clone(); + assert_same(&a, &b, "before"); + run(&mut a, "edit.cut", json!({})); + reference_cut(&mut b); + assert_same(&a, &b, "Cut"); + let after = a.doc().unwrap().doc.clone(); + run(&mut a, "edit.undo", json!({})); + run(&mut b, "edit.undo", json!({})); + assert_same(&a, &b, "Undo"); + assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document"); + run(&mut a, "edit.redo", json!({})); + run(&mut b, "edit.redo", json!({})); + assert_same(&a, &b, "Redo"); + assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut"); + run(&mut a, "edit.undo", json!({})); + run(&mut a, "edit.redo", json!({})); + a +} + +/// A new document; [`rect`] adds squares to it. +fn new_doc() -> Session { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 800, "height": 600})); + s +} + +/// Adds a 10 pt square to the current layer, 20 pt right of the last one. +fn rect(s: &mut Session) -> NodeId { + let x = 20.0 * s.doc().unwrap().doc.node_count() as f64; + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Makes a compound path of `ids` and returns it with its members in order. +fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec) { + run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::>()})); + let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect(); + (c, members) +} + +/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed. +fn three_anchors() -> Value { + json!([[0, 0], [0, 1], [0, 2]]) +} + +/// Anchors 0 and 1 of a square: Cut keeps its other three sides. +fn two_anchors() -> Value { + json!([[0, 0], [0, 1]]) +} + +/// The compound path whose members are cut one whole and one emptied goes with them; the other +/// compound path keeps its one member left, as a compound path. +#[test] +fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() { + let make = || { + let mut s = new_doc(); + let first = [(); 2].map(|()| rect(&mut s)); + let (gone, gone_members) = compound(&mut s, &first); + let second = [(); 3].map(|()| rect(&mut s)); + let (kept, kept_members) = compound(&mut s, &second); + let other = rect(&mut s); + select_direct( + &mut s, + &[gone_members[0], kept_members[0]], + &[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())], + ); + (s, gone, kept, kept_members[2], other) + }; + let s = same_as_one_at_a_time(|| make().0); + let (_, gone, kept, left, other) = make(); + let d = &s.doc().unwrap().doc; + assert!(d.node(gone).is_none(), "the compound path whose members all went is removed"); + let kept = d.node(kept).expect("the compound path with a member left stays"); + assert!(matches!(kept.kind, NodeKind::Compound { .. })); + assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::>(), [left]); + assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected"); +} + +/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept +/// siblings, keep the order and ids that removing them one at a time leaves. +#[test] +fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::>()})); + run(&mut s, "object.group", json!({})); + let b = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::>()})); + run(&mut s, "object.group", json!({})); + let c = [(); 4].map(|()| rect(&mut s)); + select_direct( + &mut s, + &[a[0], a[2], b[3], c[1]], + &[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())], + ); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected"); +} + +/// Selected ruler guides go with the objects, in the Cut's undo step. +#[test] +fn cut_removes_the_selected_guides_with_the_objects() { + let make = || { + let mut s = new_doc(); + let [a, b, c] = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 30})); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 40})); + select_direct(&mut s, &[a, c], &[(b, two_anchors())]); + run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true})); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed"); + assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard"); +} + +/// Roots that are not separate (one inside another) are removed one at a time, as before. +#[test] +fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::>()})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + let b = rect(&mut s); + select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]); + (s, vec![a[1], group, b]) + }; + let (mut x, roots) = make(); + let (mut y, _) = make(); + copy(&mut x, &json!({})).unwrap(); + copy(&mut y, &json!({})).unwrap(); + cut_direct_selection(&mut x, &roots).unwrap(); + cut_one_at_a_time(&mut y, &roots).unwrap(); + assert_same(&x, &y, "Cut"); +} + +/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and +/// anchors 0 and 1 of the square after them picked. +fn many() -> Session { + let mut s = session(10_001, square); + let ids = crate::tests_large_edits::layer(&s, 0); + let whole: Vec = ids.iter().take(10_000).step_by(5).copied().collect(); + select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]); + s +} + +/// The tree walks [`tree_walks`] counts while `f` runs on `s`. +fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 { + let before = tree_walks(); + f(s); + tree_walks() - before +} + +/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's +/// tree a few times, where removing them one at a time walks it several times for each object. +#[test] +fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() { + let s = same_as_one_at_a_time(many); + assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001); + let (mut a, mut b) = (many(), many()); + let batched = walks(&mut a, |s| { + run(s, "edit.cut", json!({})); + }); + let one_at_a_time = walks(&mut b, reference_cut); + println!("tree walks: Cut {batched}, one at a time {one_at_a_time}"); + assert!(batched <= 64, "Cut walked the document's tree {batched} times"); + assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}"); +} + +/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux). +fn cpu_time() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The middle of `v`. +fn median(mut v: Vec) -> Duration { + v.sort_unstable(); + v[v.len() / 2] +} + +/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's +/// CPU and wall-clock time with the medians. Run it with +/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`. +#[test] +#[ignore = "timing; prints the numbers"] +fn direct_selection_cut_timing() { + let mut runs: [(Vec, Vec); 2] = Default::default(); + for round in 0..7 { + for (k, (cpu, wall)) in runs.iter_mut().enumerate() { + let mut s = many(); + let (c0, w0) = (cpu_time(), Instant::now()); + if k == 0 { + reference_cut(&mut s); + } else { + run(&mut s, "edit.cut", json!({})); + } + let w = w0.elapsed(); + let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w); + println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]); + cpu.push(c); + wall.push(w); + } + } + for (k, (cpu, wall)) in runs.into_iter().enumerate() { + println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall)); + } +} diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index e80c1b2d36..868f6f5c5c 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec { "Map Graphic", [], None, - "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", + "{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", has_doc, map_graphic ), @@ -113,22 +113,32 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { if !effects::takes_graphics(&effect.id) { return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN))); } - // A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again, - // but has no cap to show a new one on. + // A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned + // on again, but has no cap to show a new one on. Its side takes graphics. let merged = effects::merged_params(&effect.id, &effect.params); let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged)); - if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { + let side = base.face == effects::PlanarFace::Side; + if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0))); } // With a depth of 0 the art is a plane, which has only a front. - if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) { + if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) { return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0))); } let mut graphic = base.clone(); if p.get("scale").is_none() - && let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol)) + && let Some(art) = effects::graphic_bounds(d, &graphic.symbol) { - graphic.scale = frame.fitting_scale(art); + // A graphic on the side starts fitting inside the side unrolled about x = 0, short of + // its cut; one on a cap inside the object's bounds. + let fit = if side { + effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art)) + } else { + effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art)) + }; + if let Some(fit) = fit { + graphic.scale = fit; + } } let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic); effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs index a9d3a754ce..35fd4cc893 100644 --- a/crates/engine/src/cmd/effectcmd/graphics_tests.rs +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok()); } +#[test] +fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() { + let (mut s, id) = setup("threeD.extrude"); + // A hollow Extrude & Bevel takes a graphic on its side. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}])); + // A plane, and a depth of 0, have no side. + let (mut s, plane) = setup("threeD.rotate"); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + let (mut s, flat) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + // A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is + // about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is + // 11 × 21. + let (mut s, id) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap(); + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}"); + // A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the + // part about x = 0 is three quarters of the outline. + let (mut s, id) = setup("threeD.extrude"); + let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap(); + let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap(); + assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}"); + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}"); +} + #[test] fn set_params_edits_graphics_and_checks_them() { let (mut s, id) = setup("threeD.extrude"); 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.rs b/crates/engine/src/cmd/fileio.rs index 86c72dec0e..cd6ec30f0d 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -65,6 +65,7 @@ pub mod zip; use serde_json::{Value, json}; +pub(crate) use action_batch::action_step; pub use action_batch::batch_overwrites_one_file; pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ @@ -95,7 +96,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend pub(crate) use native::preview_png; pub use native::with_compression_pref; pub(crate) use pdfimport::opened_page_document; -pub use pdfimport::{LoadOptions, page_document}; +pub use pdfimport::{LoadOptions, page_document, pages_can_link}; pub(crate) use psdlayers::import_active as psd_layers; pub use psdlayers::{PsdInfo, info as psd_info}; pub(crate) use psdslices::over as psd_slices; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 1ded8d1f0b..8ca1fedcd7 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p } /// Does a file of a document with `artboards` artboards, written in format `format` with options -/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and -/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` +/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates, +/// EPS files and the files of an exporter plug-in's format (`plugin.`, whose plug-in is given +/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` /// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and /// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF /// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder @@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false)); match format { "svg" | "svgz" | "vectorcraft" | "template" | "eps" => true, + _ if vectorcraft_plugins::export::plugin_id(format).is_some() => true, "ai" | "ait" => { let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false)); !legacy && !(format == "ai" && art_page()) && every_artboard() @@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu /// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`: /// always, unless read roots are in force, the file carries the native document (a native file or -/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as +/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter +/// plug-in's file, as /// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file /// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the /// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be @@ -294,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). @@ -302,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 @@ -321,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/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 4e99f4ee3e..aa3be78e2a 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { } for (i, c) in cmds.iter().enumerate() { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + let refuse = |reason: &str| bad(C, action_step(i, id, reason)); if id.is_empty() { - return Err(bad(C, format!("commands[{i}]: missing `command`"))); + return Err(refuse("missing `command`")); } if id == "command.batch" || id == "action.batch" { - return Err(bad(C, "batches cannot nest")); + return Err(refuse("batches cannot nest")); } // `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays. if id == "prefs.import" { - return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step"))); + return Err(refuse("`prefs.import` runs on its own, not as a batch step")); } if find_command(id).is_none() { - return Err(bad( - C, - match super::super::params::nearest_command(id) { - Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"), - None => format!("commands[{i}]: unknown command `{id}`"), - }, - )); + return Err(refuse(&super::super::params::unknown_command(id).to_string())); } } // Every option is checked before the destination folder is made. @@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)), }; match c.get("command").and_then(Value::as_str).unwrap_or("") { - "document.save" | "file.save" => !save && (path || own_file()), + "document.save" => !save && (path || own_file()), "file.saveAs" => !save && path, "file.saveCopy" | "file.saveAsTemplate" => path, "document.export" | "document.exportSelection" => !export && path, @@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool { /// in the destination folder when `redirected`) and makes that file the document's own: a save in /// the native template format writes a copy and leaves the document's file as it was. fn retargeting_save(c: &Value, redirected: bool) -> bool { - if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) { + if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) { return false; } let params = c.get("params"); @@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: // open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a // source file in the destination folder, other than that file's own output, or of a subfolder // of the destination folder that holds source files. - let (steps, places) = filter_steps(run.steps, override_open, false); + let (steps, places) = filter_steps(run.steps, override_open); let run = Run { steps: &steps, ..*run }; let in_dest: Vec> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect(); let mut picker = @@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; - let (steps, places) = filter_steps(run.steps, true, false); + let (steps, places) = filter_steps(run.steps, true); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); let mut failed = 0usize; @@ -353,22 +348,13 @@ impl StemPicker { } } -/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that -/// stay, and the index of each in `cmds`. +/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the +/// steps that stay, and the index of each in `cmds`. #[cfg(not(target_arch = "wasm32"))] -fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec, Vec) { +fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec, Vec) { cmds.iter() .enumerate() - .filter(|(_, c)| { - let id = c.get("command").and_then(Value::as_str).unwrap_or(""); - if drop_open && matches!(id, "document.open" | "file.open") { - return false; - } - if drop_close && matches!(id, "file.close" | "document.close") { - return false; - } - true - }) + .filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open"))) .map(|(i, c)| (c.clone(), i)) .unzip() } @@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)), + Some(&place) if same => EngineError::Other(action_step(place, id, reason)), _ => e, } }) } +/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with +/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The +/// checks before a batch runs and the errors of its steps as they run give the same text. +pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String { + let n = index.saturating_add(1); + if id.is_empty() { + format!("action step {n} failed: {reason}") + } else { + format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id)) + } +} + /// The step number, command id and reason in the error `command.batch` gives when one of its steps /// fails (``batch step 2 (`object.move`) failed: …``); none for any other error. #[cfg(not(target_arch = "wasm32"))] @@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true }); continue; } - let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs")) || (run.override_export && matches!(id, "document.export" | "document.exportSelection")); if writes { let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); @@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def }; if safe_extension(&ext) { let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft"); - let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let is_save = matches!(id, "document.save" | "file.saveAs"); let artboards = if is_save { !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") } else { @@ -693,7 +691,7 @@ fn rewrite_paths( .map(|c| { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); let mut c = c.clone(); - let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs")) || (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export")); if !rewrite { return c; @@ -2385,10 +2383,97 @@ mod tests { let mut s = Session::new(); let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]}); let e = s.execute("action.batch", &p).unwrap_err().to_string(); - assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}"); + assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}"); assert!(s.active().is_none(), "no file was opened"); } + /// Each step the checks before the batch refuse is named by its place in `commands`, from 1, + /// as a step that fails as it runs is, and no source file is opened. + #[test] + fn a_refused_step_is_named_by_its_place_from_1() { + let src = tmp("step-number-refused-src"); + write_svg(&src, "a.svg", "#f00"); + let prefix = "invalid parameters for `action.batch`: "; + let cases = [ + (json!({"params": {}}), "action step 2 failed: missing `command`"), + (json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"), + (json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"), + (json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"), + ( + json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}), + "action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0", + ), + ]; + for (step, want) in cases { + let mut s = Session::new(); + let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]}); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert_eq!(e, format!("{prefix}{want}"), "{step}"); + assert!(s.active().is_none(), "{step}: a file was opened"); + assert!(s.journal.is_empty(), "{step}: a step ran"); + } + } + + /// The parameter check of an `action.batch` names the step whose params it refuses, from 1; + /// that of a `command.batch` passes the step's error on as it is. + #[test] + fn the_parameter_check_names_the_refused_step() { + let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}); + let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]); + let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0"; + let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}")); + let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, own); + } + + /// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and + /// `document.close` are not engine commands, so a step with one is refused before the batch + /// starts, with Override Open and Override Save on or off. + #[test] + fn steps_with_ids_that_are_not_engine_commands_are_refused() { + let src = tmp("step-number-aliases-src"); + write_svg(&src, "a.svg", "#f00"); + for id in ["file.open", "file.save", "document.close"] { + for overrides in [true, false] { + let mut s = Session::new(); + let p = json!({ + "folder": src.to_string_lossy(), + "overrideOpen": overrides, + "overrideSave": overrides, + "commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}], + }); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert!( + e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")), + "{e}" + ); + assert!(s.active().is_none(), "{id}: a file was opened"); + } + } + } + + /// `command.batch` keeps its own numbering, from 0, for a step that fails. + #[test] + fn command_batch_keeps_its_own_step_numbers() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s + .execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]})) + .unwrap_err(); + assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}"); + } + + /// A step's id in the error is cut short, as an unknown key's is. + #[test] + fn a_long_step_id_is_cut_short() { + let id = "x".repeat(10_000); + let shown = action_step(0, &id, "why"); + assert!(shown.len() < 1_000, "{}", shown.len()); + assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}"); + assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX)); + } + /// Only the error `command.batch` gives for a failed step is read as one. #[test] fn batch_step_failure_reads_only_a_step_error() { diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index adc73c2c85..0969adb5a2 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8486cd2226..8004234c07 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> vec![(Some(b), rect(b)?, false)] } }; + let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect(); + let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for (board, region, crop) in drawings { - let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?; + for ((board, _, _), out) in drawings.into_iter().zip(outs) { enc.files.push((board, out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 3e34dae7f2..8b5cd9fe6f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { /// The file exporter plug-in `plugin` writes of `doc` in its format `f` /// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON -/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else -/// one named after the document) with that path's extension when the plug-in lists it, else its -/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind). +/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots +/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path` +/// names (else one named after the document) with that path's extension when the plug-in lists it, +/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind). fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result { use vectorcraft_plugins::{Error, export}; - let doc = &*doc.without_edit_modes(); + let doc = doc.without_edit_modes(); + let doc = &*super::access::with_readable_settings_folder(&doc); let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?; let path = p.get("path").and_then(Value::as_str); let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e)); 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 d987d82757..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,13 +38,20 @@ 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(); - for b in boards { - let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect; - let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?; + for (b, out) in boards.into_iter().zip(outs) { enc.files.push((Some(b), out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 0adc827df0..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; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; 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; 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), 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/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 189274a31f..ea37575135 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } +/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a +/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password +/// and `textAs` are checked apart ([`linked_pages`]). +pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { + bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes) +} + /// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page 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_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 1a3368b56f..b5129d1910 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() { assert!(e.contains("useArtboards"), "{e}"); } +#[test] +fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() { + let mut s = two_boards(); + // A second rectangle on the second artboard, so the two drawings differ. + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap(); + let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap(); + let files = r["files"].as_array().unwrap(); + let doc = &s.doc().unwrap().doc; + let o = dxf::options(&json!({"unit": "pt"})).unwrap(); + assert_eq!(files.len(), doc.artboards.len()); + assert_ne!(b64(&files[0]), b64(&files[1])); + for (f, board) in files.iter().zip(&doc.artboards) { + let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap(); + assert_eq!(b64(f), alone.bytes, "{}", f["name"]); + } +} + #[test] fn selected_only_exports_the_selection_in_its_layers() { let mut s = two_boards(); 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_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index 703c29fe74..63b70c48c7 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() { assert!(open(&mut s, &two, json!({"pages": "1"})).is_err()); open(&mut s, &two, json!({})).unwrap(); } + +/// `linkPages` takes a PDF up to the largest file placed, and nothing else. +#[test] +fn pages_can_link_a_pdf_up_to_the_largest_file_placed() { + let small = three_pages(); + assert!(pages_can_link("pages.pdf", &small)); + assert!(!pages_can_link("pages.svg", b"")); + let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1]; + big[..small.len()].copy_from_slice(&small); + assert!(!pages_can_link("pages.pdf", &big), "over the limit"); + big.pop(); + assert!(pages_can_link("pages.pdf", &big), "at the limit"); +} 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/fonts.rs b/crates/engine/src/cmd/fonts.rs index 45689adc17..ef7420217b 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -532,6 +532,24 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc], areas: super::typecmd::export_overflow_warning(&overflow) } +/// The objects behind production findings. Resource art points to its first visible owner on +/// the canvas, so a finding can be located without selecting an id outside the layer tree. +#[derive(Default)] +pub(super) struct PreflightType { + pub fonts: BTreeMap>, + pub overflow: BTreeSet, + pub images: BTreeMap, +} + +pub(super) fn preflight_type(d: &Document, layers: &[Arc], areas: &[Rect]) -> PreflightType { + let mut walk = Printed::new(d); + walk.preflight = Some(PreflightType::default()); + for l in layers { + walk.node(l, Some(areas)); + } + walk.preflight.unwrap_or_default() +} + /// The walk of [`printed_type`]. struct Printed<'a> { d: &'a Document, @@ -546,13 +564,25 @@ struct Printed<'a> { /// The symbols and patterns whose art was walked. symbols: BTreeSet, patterns: BTreeSet, + preflight: Option, + owner: Option, } impl<'a> Printed<'a> { /// A walk of `d` among its own objects, nothing found yet. fn new(d: &'a Document) -> Self { let boxes = d.symbol_boxes(); - Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() } + Self { + d, + boxes, + own: true, + fonts: BTreeSet::new(), + overflow: BTreeSet::new(), + symbols: BTreeSet::new(), + patterns: BTreeSet::new(), + preflight: None, + owner: None, + } } /// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit @@ -560,6 +590,15 @@ impl<'a> Printed<'a> { /// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live /// object) all of them but those outside the clipping path of a clip group. fn node(&mut self, n: &Node, areas: Option<&[Rect]>) { + let previous = self.owner; + if self.own { + self.owner = Some(n.id); + } + self.node_contents(n, areas); + self.owner = previous; + } + + fn node_contents(&mut self, n: &Node, areas: Option<&[Rect]>) { if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) { return; } @@ -571,6 +610,14 @@ impl<'a> Printed<'a> { && !open && !self.meets(n, a) { + // An entirely overset frame paints nothing, but is still a delivery problem. Keep + // the export walk unchanged; only preflight checks the frame itself in this case. + if let (Some(p), Some(owner), NodeKind::Text(t)) = (&mut self.preflight, self.owner, &n.kind) + && n.geometric_bounds().is_some_and(|b| a.iter().any(|r| r.intersect(b).area() > 0.0 || r.contains_rect(b))) + && vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).overflow + { + p.overflow.insert(owner); + } return; } // The art that its opacity mask, pattern paints and brushed strokes draw. @@ -616,16 +663,33 @@ impl<'a> Printed<'a> { if overflows && self.own { self.overflow.insert(n.id); } + if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + p.overflow.insert(owner); + } for r in runs { - self.fonts.extend(run_fonts(r)); + let fonts = run_fonts(r); + if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + for font in &fonts { + p.fonts.entry(font.clone()).or_default().insert(owner); + } + } + self.fonts.extend(fonts); // Inline graphics draw their symbols' art. if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) { self.symbol(&art.symbol); } } } + NodeKind::Image(_) => { + if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) { + p.images.entry(n.id).or_insert(owner); + } + } NodeKind::SymbolInstance { symbol, .. } => self.symbol(symbol), NodeKind::PlacedDocument(p) => { + if let (Some(report), Some(owner)) = (&mut self.preflight, self.owner) { + report.images.entry(n.id).or_insert(owner); + } for art in p.art(n) { self.art(&art); } diff --git a/crates/engine/src/cmd/inline.rs b/crates/engine/src/cmd/inline.rs index 784548e491..676fb9b55b 100644 --- a/crates/engine/src/cmd/inline.rs +++ b/crates/engine/src/cmd/inline.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::text::INLINE_MAX_SCALE; -use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun}; +use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun}; use vectorcraft_text::edit; use super::brushsym::current_symbol; @@ -25,12 +25,33 @@ pub fn specs() -> Vec { /// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols, /// resolve the inline art of every text again, in the layers and in the art of symbols, graph /// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a -/// symbol's type before the type that shows that symbol inline). -pub(crate) fn refresh(before: &Document, d: &mut Document) { +/// symbol's type before the type that shows that symbol inline). `last` is the document the last +/// refresh left resolved, with what it measured: when nothing the inline art depends on changed +/// since, only the layer trees that differ from its own are checked +/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when +/// neither document has symbols and nothing was checked. +pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option { if before.symbols.is_empty() && d.symbols.is_empty() { - return; + return None; } - d.resolve_inline_art_with(&mut refresh_bounds); + #[cfg(test)] + let last = last.filter(|_| !FULL_PASS.get()); + let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds); + #[cfg(test)] + PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone()))); + Some(pass.measured) +} + +/// A document a [`refresh`] left resolved, and what that refresh measured. +pub(crate) type Resolved = (std::sync::Arc, InlineMeasured); + +#[cfg(test)] +thread_local! { + /// Each [`refresh`] on this thread that checked the document: whether it checked only the + /// changed layer trees, and the ids of the texts in the layers that changed. + pub(crate) static PASSES: std::cell::RefCell)>> = const { std::cell::RefCell::new(vec![]) }; + /// Set: every [`refresh`] on this thread takes the full pass. + pub(crate) static FULL_PASS: std::cell::Cell = const { std::cell::Cell::new(false) }; } fn insert_inline(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 237f0f9d49..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, @@ -29,7 +30,7 @@ pub fn specs() -> Vec { "New Layer…", ["Window", "Layers"], Some("Cmd+L"), - "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", + "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", super::maskedit::outside_mask_editing, new_layer ), @@ -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. 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 ), @@ -526,12 +527,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO fn new_layer(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.new"; let below = switch_or(p, "below", false, C)?; - if below && bool_or(p, "top", false) { + let top = bool_or(p, "top", false); + if below && top { return Err(bad(C, "`top` and `below` can't both be true")); } + // In Draw Behind a layer given neither `top` nor `below` goes below the current layer. + let below = below || (!top && s.draw_mode == crate::DrawMode::Behind); let st = s.doc()?; // Above the current layer, at its level; below it with `below`; on top of everything with `top`. - let cur = st.current_layer().filter(|_| !bool_or(p, "top", false)); + let cur = st.current_layer().filter(|_| !top); add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) { Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })), None => Ok((None, if below { 0 } else { usize::MAX })), @@ -622,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); } } @@ -648,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); @@ -723,19 +741,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result { } else { vec![id] }; - let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let all_selected = add && !ids.is_empty() && { + let selected: HashSet = st.selection.objects.iter().copied().collect(); + ids.iter().all(|i| selected.contains(i)) + }; let rows = st.layer_rows.clone(); s.select(|_, sel| { if !add { sel.set(ids.iter().copied()); } else if all_selected { - for i in &ids { - sel.remove(*i); - } + sel.remove_all(ids.iter().copied()); } else { - for i in &ids { - sel.add(*i); - } + sel.add_all(ids.iter().copied()); } })?; let st = s.doc_mut()?; @@ -774,9 +791,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "no such rows")); } - // Never into itself or a row inside it. + // Never into itself or a row inside it. A copy may go above or below one of the rows it + // copies, which a move there would leave where it is (#8237). + let beside_itself = copy && place != Place::Inside && ids.contains(&target); let around = d.ancestry(target).unwrap_or_default(); - if ids.iter().any(|i| around.contains(i)) { + if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) { return Err(bad(C, "a row can't go into itself")); } let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect(); @@ -788,6 +807,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { parent => (parent, Some(target)), }, }; + // A copy beside a top-level layer it copies, with objects among the rows, would go inside + // that layer: into itself. + if parent.is_some_and(|p| ids.contains(&p)) { + return Err(bad(C, "a row can't go into itself")); + } if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) { let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() }); return Err(bad(C, format!("{} can't go into {into}", n.display_name()))); @@ -798,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(); @@ -839,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) @@ -861,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 95c152e959..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?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}", + "{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 ), @@ -435,10 +435,20 @@ fn reverse(s: &mut Session, p: &Value) -> Result { 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"))?; - let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; - st.layer_rows = vec![id]; + // 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). + let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?; + ancestry.truncate(at + 1); + } + let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?; + st.layer_rows = vec![row]; + st.locate_reveal = Some(row); st.revision += 1; - Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::>() })) + let ancestry: Vec = ancestry.iter().map(|i| i.0).collect(); + Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) }) } 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.rs b/crates/engine/src/cmd/live.rs index 618865cede..1d23d07792 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -29,6 +29,8 @@ mod commands; mod common; mod envelope; mod mesh; +#[cfg(test)] +mod selected_tests; pub(crate) use blend::expand_blends; pub use commands::specs; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 5334311789..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; @@ -657,9 +694,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result { } /// Is any selected blend one made without a spine? -fn any_without_spine(s: &Session) -> bool { - let Ok(st) = s.doc() else { return false }; - selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +pub(super) fn any_without_spine(s: &Session) -> bool { + super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine)) } pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result { 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/live/common.rs b/crates/engine/src/cmd/live/common.rs index cfa3f32076..661d574b58 100644 --- a/crates/engine/src/cmd/live/common.rs +++ b/crates/engine/src/cmd/live/common.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use super::mesh::whole; use super::{ Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value, @@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { let mut sel = Selection::default(); sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer()))); let ordered = sel.in_paint_order(&st.doc); + let given: HashSet = ordered.iter().copied().collect(); // Drop ids nested inside other given ids. return Ok(ordered .iter() .copied() .filter(|id| { let anc = st.doc.ancestry(*id).unwrap_or_default(); - !anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a)) + !anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a)) }) .collect()); } @@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { /// dynamic symbol instance's art is selected. pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec { let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut find = st.doc.nearest_finder(); + let mut seen = HashSet::new(); let mut out = vec![]; for id in &st.selection.objects { - for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { - if st.doc.node(a).is_some_and(pred) { - if !out.contains(&a) { - out.push(a); - } - break; - } + if let Some(n) = find.nearest(*id, pred) + && seen.insert(n.id) + { + out.push(n.id); } } out } +/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the +/// first one that does. +pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false }; + let mut find = st.doc.nearest_finder(); + st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test)) +} + pub(super) fn is_blend(n: &Node) -> bool { matches!(n.kind, NodeKind::Blend { .. }) } @@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool { pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) } + if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) } } pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) } + if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) } } pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) } + if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) } } /// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was. diff --git a/crates/engine/src/cmd/live/selected_tests.rs b/crates/engine/src/cmd/live/selected_tests.rs new file mode 100644 index 0000000000..b1250e2560 --- /dev/null +++ b/crates/engine/src/cmd/live/selected_tests.rs @@ -0,0 +1,324 @@ +//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones +//! the lookup of every ancestor by id found: the same ids in the same order, the same availability +//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use serde_json::json; +use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart}; + +use super::Session; +use super::blend::any_without_spine; +use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of}; + +/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from +/// the object up, repeats dropped by a scan of the list. +fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut out = vec![]; + for id in &st.selection.objects { + for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { + if st.doc.node(a).is_some_and(pred) { + if !out.contains(&a) { + out.push(a); + } + break; + } + } + } + out +} + +/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`]. +fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> { + super::has_selection(s)?; + crate::cmd::edit::no_symbol_part(s)?; + if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) } +} + +/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`]. +fn without_spine_by_ids(s: &Session) -> bool { + let Ok(st) = s.doc() else { return false }; + selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +} + +/// Every check on the current selection gives what the lookups by id gave. +fn agree(s: &Session, what: &str) { + type Has = fn(&Session) -> std::result::Result<(), String>; + for (name, pred, has, msg) in [ + ("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"), + ("envelope", is_envelope, has_envelope, "select an envelope"), + ("mesh", is_mesh, has_mesh, "select a gradient mesh"), + ] { + let want = selected_of_by_ids(s, pred); + assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s"); + assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}"); + assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}"); + } + assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine"); +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId { + select(s, ids); + id_of(&s.execute(cmd, &p).unwrap()) +} + +/// Every node id under the layers, parents before children (as Direct Selection can pick them). +fn all_ids(s: &Session) -> Vec { + fn walk(nodes: &[std::sync::Arc], out: &mut Vec) { + for n in nodes { + out.push(n.id); + if let Some(ch) = n.children() { + walk(ch, out); + } + } + } + let mut out = vec![]; + for l in &s.doc().unwrap().doc.layers { + walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out); + } + out +} + +/// The active document, to change in place. +fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) +} + +/// Set the selection's objects as given, stale and repeated ids included. +fn set_objects(s: &mut Session, ids: Vec) { + s.doc_mut().unwrap().selection.objects = ids; +} + +/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine. +/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key +/// of `a`. +fn document() -> (Session, [NodeId; 6]) { + let mut s = session(); + let r: Vec = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect(); + let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({})); + let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({})); + let g = run(&mut s, "object.group", &[a, r[4]], json!({})); + let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({})); + let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50})); + select(&mut s, &[r[7]]); + s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap(); + if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) { + spec.no_spine = true; + } + (s, [a, b, c, g, e, r[0]]) +} + +#[test] +fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() { + let (mut s, [a, b, c, g, e, inner_key]) = document(); + s.execute("select.all", &json!({})).unwrap(); + agree(&s, "select all"); + let all = all_ids(&s); + let keys: Vec = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect(); + set_objects(&mut s, keys.clone()); + agree(&s, "keys, as Direct Selection picks them"); + set_objects(&mut s, all.iter().rev().copied().collect()); + agree(&s, "every node, children first"); + set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]); + agree(&s, "repeated and stale ids, in first-seen order"); + assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order"); + set_objects(&mut s, vec![NodeId(999_999)]); + agree(&s, "only a stale id"); + set_objects(&mut s, vec![]); + agree(&s, "nothing"); + // A blend in another blend's key group: the inner one. + set_objects(&mut s, vec![inner_key]); + agree(&s, "a key of a blend nested in another's key group"); + assert_eq!(selected_of(&s, is_blend), vec![a]); + // An object of a dynamic symbol instance's art: nothing. + set_objects(&mut s, all.clone()); + s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] }); + agree(&s, "a symbol part"); + assert!(selected_of(&s, is_blend).is_empty()); +} + +/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's +/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is +/// built again. +#[test] +fn a_repeated_id_counts_as_its_first_node() { + let (mut s, [a, _, c, _, _, inner_key]) = document(); + let all = all_ids(&s); + s.doc().unwrap().doc.node(a); + let doc = doc_mut(&mut s); + if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() { + ch.insert(0, std::sync::Arc::new(Node::group(a, vec![]))); + } + set_objects(&mut s, all.clone()); + agree(&s, "a repeated id, the cache older than the tree"); + s.doc().unwrap().doc.drop_lookup_cache(); + agree(&s, "a repeated id, no cache"); + s.doc().unwrap().doc.node(a); + agree(&s, "a repeated id, cached afresh"); + set_objects(&mut s, vec![inner_key]); + assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts"); +} + +/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and +/// the checks stop at the first selected object that has one. +#[test] +fn selected_blends_take_no_lookups_by_id() { + let mut s = session(); + let mut keys = vec![]; + for i in 0..300 { + let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0)); + run(&mut s, "object.blend.make", &[x, y], json!({})); + keys.extend([x, y]); + } + for i in 0..1_000 { + rect(&mut s, i as f64); + } + s.execute("select.all", &json!({})).unwrap(); + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(keys[0]); + let before = vectorcraft_doc::path_lookups(); + assert_eq!(selected_of(&s, is_blend).len(), 300); + assert!(!any_selected_of(&s, is_mesh, |_| true)); + set_objects(&mut s, keys.clone()); + assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys"); + assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id"); + // The first key is in a blend: the check tests that key and its blend only. + static TESTED: AtomicUsize = AtomicUsize::new(0); + fn counted(n: &Node) -> bool { + TESTED.fetch_add(1, Ordering::Relaxed); + is_blend(n) + } + assert!(any_selected_of(&s, counted, |_| true)); + assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested"); +} + +/// `n` and everything under it with new ids. +fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node { + let mut n = n.clone(); + n.id = d.alloc_id(); + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + *c = std::sync::Arc::new(renumber(d, c)); + } + } + n +} + +/// This thread's CPU time in nanoseconds, where the system reports it (Linux). +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it, +/// otherwise in wall-clock time. +fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 { + let (cpu, wall) = (cpu_ns(), std::time::Instant::now()); + for _ in 0..calls { + f(); + } + let ms = match (cpu, cpu_ns()) { + (Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1e3, + }; + ms / f64::from(calls) +} + +/// The medians of 7 runs of `a` and of `b`, the runs taking turns. +fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) { + let (mut ta, mut tb) = (vec![], vec![]); + for _ in 0..7 { + ta.push(ms_per_call(calls, a)); + tb.push(ms_per_call(calls, b)); + } + ta.sort_by(f64::total_cmp); + tb.sort_by(f64::total_cmp); + (ta[3], tb[3]) +} + +/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers, +/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with +/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn timing_of_the_selected_blend_checks() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0)); + let square = rect(&mut s, 120.0); + let blend = run(&mut s, "object.blend.make", &[a, b], json!({})); + let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50})); + let doc = doc_mut(&mut s); + let templates: Vec = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect(); + let mut layers = vec![]; + for l in 0..10 { + let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0)); + let mut kids = vec![]; + for _ in 0..10_000 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[0]))); + } + for i in 0..200 { + let b = renumber(doc, &templates[1]); + let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b }; + kids.push(std::sync::Arc::new(b)); + } + for _ in 0..20 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[2]))); + } + if let Some(ch) = layer.children_mut() { + *ch = kids; + } + layers.push(std::sync::Arc::new(layer)); + } + doc.layers = layers; + s.execute("select.all", &json!({})).unwrap(); + let first = s.doc().unwrap().selection.objects[0]; + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(first); + println!("{} objects selected", s.doc().unwrap().selection.objects.len()); + type Check = fn(&Session) -> bool; + let checks: [(&str, Check, Check); 5] = [ + ("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()), + ("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()), + ("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()), + ( + "selected blends (object.blend.info and the Blend commands)", + |s| !selected_of_by_ids(s, is_blend).is_empty(), + |s| !selected_of(s, is_blend).is_empty(), + ), + ("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine), + ]; + assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend)); + println!("| Check | Lookups by id (ms) | One path (ms) |"); + println!("|---|---:|---:|"); + for (name, by_ids, one_path) in checks { + assert_eq!(by_ids(&s), one_path(&s), "{name}"); + let (old, new) = medians( + 15, + &|| { + std::hint::black_box(by_ids(&s)); + }, + &|| { + std::hint::black_box(one_path(&s)); + }, + ); + println!("| {name} | {old:.3} | {new:.3} |"); + } +} 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/newart.rs b/crates/engine/src/cmd/newart.rs index ce8029e71b..84812dad97 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -7,12 +7,16 @@ //! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the //! option on (the default) an inherited appearance gives new art its top stroke's options only, //! and a change of selection loads only the proxies. `paint.default` resets it. +//! +//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile +//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new` +//! resets new art when it opens such a document. use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; use vectorcraft_tools::PaintDefaults; use super::gradient::unplaced; @@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result { })) } -/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template. +/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template; +/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects +/// at full opacity, not linked to the style. pub(crate) fn reset(s: &mut Session) { s.paint = PaintDefaults::default(); + let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned(); + if let Some(g) = style { + let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) }; + s.take_new_art(ap, 1.0, BlendMode::Normal, None, false); + } +} + +/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the +/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode +/// as a New Document profile's are. +pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> { + let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?; + let same = + |o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout); + if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) { + return None; + } + if d.color_mode != ColorMode::Rgb { + let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb); + shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE); + super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile); + if shipped.graphic_styles.first().is_some_and(same) { + return None; + } + } + Some(g) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 2a8d074617..e74a570a5b 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // The profile's links keep their relative paths, which name places from the profile's file, as // a new document from a history state keeps its source's. s.doc_mut()?.links_from = links_from; + // A profile whose Default Graphic Style was redefined gives new art in the document that style. + if super::newart::redefined_default_style(&s.doc()?.doc).is_some() { + super::newart::reset(s); + } // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both // are views of the whole app, so Default leaves them as they are. if settings.preview_mode == PreviewMode::Overprint { diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a58f206c84..fd0aece164 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{ }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub use transform::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 17568d50b9..4250f3c377 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -371,19 +371,29 @@ 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 { + let key = "all"; + let all = match p.get(key) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?, + }; // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's // Done do. A group isolated inside the symbol's art goes back to the symbol's layer. @@ -419,12 +429,18 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { return ok(); } let menu = s.menu.clone(); - let prev = s.active().and_then(|d| d.isolation); + let prev = st.isolation; + // An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or + // that layer is hidden or locked; anything else leaves isolation mode. + let up = prev + .filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer)) + .and_then(|i| st.doc.parent_of(i)) + .filter(|parent| st.doc.is_editable(*parent)); if let Some(i) = prev { crate::cmd::settle_interaction(s)?; - let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i); + let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i); let st = s.doc_mut()?; - st.isolation = None; + st.isolation = up; crate::cmd::distortcmds::finish_edit_text(st, i); let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index cf0473f353..a24e71c9a6 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -59,7 +59,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor let refi = reference_index(p)?; let st = s.doc()?; check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?; - check_switches(p, &["proportional"], "object.setBounds")?; + check_switches(p, &["proportional", "interpolate"], "object.setBounds")?; let how = s.bounds_measure(); if anchors && transforms_objects(p) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0c638ceb5e..92f4744fea 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Transform", [], None, - "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", + "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", has_doc, transform ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Move…", ["Object", "Transform"], Some("Cmd+Shift+M"), - "{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection_or_guides, move_cmd ), @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Transform Again", ["Object", "Transform"], Some("Cmd+D"), - "{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", + "{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", has_selection, transform_again ), @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Nudge", [], None, - "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", + "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", has_selection_or_guides, nudge ), @@ -250,7 +250,7 @@ pub fn specs() -> Vec { "Exit Isolation Mode", [], None, - "{} leave isolation mode; 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 ), @@ -295,7 +295,7 @@ pub fn specs() -> Vec { "Set Bounds", [], None, - "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", + "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", has_selection, set_bounds ), @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), 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/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b30959de99..02edf6193b 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -6,6 +6,7 @@ use super::{ BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches, convert_radii_relative, ok, selected_roots, set_corners, targets, }; +use crate::MAX_COORD; /// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`, /// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across @@ -98,8 +99,32 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } +/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about +/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. +fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option { + let now = l.line_length()?; + let mut new = l.clone(); + let mut changed = false; + if let Some(len) = len + && (len - now).abs() > 1e-9 * len.max(now) + { + new.set_line_length(len); + changed = true; + } + if let Some(a) = angle + && new.line_length().is_some_and(|n| n > 0.0) + && let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0)) + && turn > 1e-9 + && turn < 360.0 - 1e-9 + { + new.set_line_angle(a); + changed = true; + } + (changed && new != *l).then_some(new) +} + pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { - check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; + check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { @@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } }; let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0))); - let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0"); + let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0"); // Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these // checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and // a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a @@ -168,21 +193,58 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?); let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true); + // Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps + // its span (its end angle less its start angle, counterclockwise). + let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true); + if constrain && (invert || pie_start.is_some() == pie_end.is_some()) { + return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`")); + } // A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal. let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?); let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true); + // A line's Line Properties: its length (its first end stays) and its angle (about its midpoint). + // A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below. + let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?; + let line_angle = angle("lineAngle")?; // An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole // ellipse as 0° to 360°). let end_of = |a: f64| if a == 0.0 { 360.0 } else { a }; let pie_of = |pie: (f64, f64)| { - let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)); + let span = (pie.1 - pie.0).rem_euclid(360.0); + let pie = match (constrain, pie_start, pie_end) { + // The angle it already has: nothing moves. + (true, Some(a), _) if a == pie.0 => pie, + (true, _, Some(a)) if end_of(a) == pie.1 => pie, + // A whole ellipse (a span of 0) stays whole. + (true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))), + (true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)), + _ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)), + }; if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie } }; // When every value given is the current one, the document and its undo history stay as they // are. let st = s.doc()?; + // The lines that Line Length or Line Angle changes, as they become. A line that would reach + // past the document's coordinate limit is an error before anything changes. + let mut lines = std::collections::BTreeMap::new(); + if line_length.is_some() || line_angle.is_some() { + for id in &ids { + let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + if let Some(new) = line_edit(l, line_length, line_angle) { + let LiveShape::Line { a, b } = &new else { continue }; + if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) { + return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } + lines.insert(*id, new); + } + } + } let has_values = |id: &NodeId| { let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true }; + if lines.contains_key(id) { + return false; + } match live.as_deref() { Some(l @ LiveShape::Polygon { sides: now, .. }) if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now)) @@ -244,6 +306,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } *path = l.to_path(); } + if let Some(new) = lines.get(id) + && let Some(l) = live.as_deref_mut() + { + *l = new.clone(); + *path = l.to_path(); + } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 25a831622e..7b1a97b4b3 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -125,9 +125,14 @@ fn apply_transform_moving_guides( let d = &s.doc()?.doc; let paths = d.index_paths(ids.iter().copied()); let none = paths.is_empty() && !has_guides; + // A move of direct-selected anchors may re-map the handles beside them (`interpolate`). + let mut interpolate = None; let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() { + if c[..4] == [1.0, 0.0, 0.0, 1.0] { + interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?); + } if xf != Affine::IDENTITY { - crate::cmd::path::transform_anchors(s, label, xf, sc)?; + crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?; } ids } else if none || (!copy && xf == Affine::IDENTITY) { @@ -195,6 +200,9 @@ fn apply_transform_moving_guides( options["strokes"] = json!(sc.strokes); options["corners"] = json!(!sc.keep_corners); } + if let Some(on) = interpolate { + options["interpolate"] = json!(on); + } st.last_transform = Some(LastTransform::Matrix(xf, options)); st.last_perspective = None; } @@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool { pub(super) fn transform(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?; - check_switches(p, &["anchors", "releaseOutside"], "object.transform")?; + check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?; let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?; // An object selected in a symbol instance's art stays where the symbol puts it: the selection // is left as it is, and the reply's warning goes to the status bar. @@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result { pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.move")?; check_switches(p, &TRANSFORM_SWITCHES, "object.move")?; + check_switches(p, &["interpolate"], "object.move")?; let ids = selected_roots_to_transform(s)?; apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true) } @@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) { pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.nudge")?; check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?; - check_switches(p, &["big"], "object.nudge")?; + check_switches(p, &["big", "interpolate"], "object.nudge")?; let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 }; let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k); // Guides keep to the page's axes; art and anchors move along the constrain angle's. @@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { if dx == 0.0 && dy == 0.0 { return ok(); } - return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") })); + return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") })); } if s.doc()?.selection.is_empty() { let copy = bool_or(p, "copy", false); @@ -360,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let sx = f64_req(p, "sx", "object.scale")? / 100.0; - let sy = f64_or(p, "sy", sx * 100.0) / 100.0; - if sx == 0.0 || sy == 0.0 { - return Err(bad("object.scale", "scale must be non-zero")); - } + let sx = f64_req(p, "sx", "object.scale")?; + let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?; let frame = basis_frame(s, p, "object.scale", &ids)?; apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true) } +/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when +/// either factor is 0. +pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> { + let (sx, sy) = (sx / 100.0, sy / 100.0); + if sx == 0.0 || sy == 0.0 { + return Err("scale must be non-zero".into()); + } + Ok((sx, sy)) +} + /// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param: /// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset /// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with @@ -393,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; // A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page. - let named = match p.get("axis") { - Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)), - Some(Value::Number(_)) => None, - None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(v) => { - let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); - return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))); - } - }; + let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?; let m = match named { Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m), None => { @@ -414,22 +421,76 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis +/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle, +/// which is a line on the page; or the error for any other value. +pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result, String> { + match axis { + Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))), + Some(Value::Number(_)) => Ok(None), + None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")) + } + } +} + +/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It +/// is far above the rounding error of an angle up to 359° and below any angle a field shows. +const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; + +/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An +/// angle outside -359 to 359, or ±90 or ±270, is an error. +pub fn shear_tangent(angle: f64) -> std::result::Result { + if !(-359.0..=359.0).contains(&angle) { + return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}")); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + let flat = angle.rem_euclid(180.0); + if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear")); + } + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }) +} + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; + let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan(); - let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); - let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; + let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]); + // A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal. + let m = match p.get("axis") { + None | Some(Value::Null) => horizontal, + Some(Value::String(a)) if a == "horizontal" => horizontal, + Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]), + Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => { + // y is down, so the page's counter-clockwise angle turns the other way on screen. + let r = -n.as_f64().unwrap_or(0.0).to_radians(); + Affine::rotate(r) * horizontal * Affine::rotate(-r) + } + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}"); + return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`"))); + } + }; apply_transform(s, "Shear", ids, about(o, m), p, true) } +/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees. +const SHEAR_AXIS_MAX: f64 = 359.0; + /// The last transform on the selection, with the options `last_transform` keeps for it; an option /// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform /// Each is repeated by running it again (its transform is per object, about each one's bounds). pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?; + check_switches(p, &["interpolate"], "object.transformAgain")?; if let Some(again) = s.doc()?.last_perspective.clone() { return crate::cmd::distortcmds::transform_again(s, &again); } 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/package.rs b/crates/engine/src/cmd/package.rs index 04c0d2ba51..e959f126c0 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Package", [], None, - "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied", has_doc, package )] @@ -113,27 +113,65 @@ thread_local! { pub(crate) static PARTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of -/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read. -fn carried_document(name: &str, bytes: &[u8]) -> Option { - if super::place::document::is_native(name, bytes) { - return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc); - } - let data = - if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) }; - vectorcraft_format::load(&data?).ok() +/// The native document a linked file is or carries ([`carried_document`]). +enum Carried { + /// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file + /// without editing data. + Absent, + /// The native document, read. + Readable(Box), + /// The file is a native document, or carries one, that can't be read: a damaged native file, + /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF + /// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file + /// whose attachments are too many to search to their end, or editing data that doesn't read as + /// a native document. + Unreadable, } +/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of +/// a PDF, `.ai` or EPS file. +fn carried_document(name: &str, bytes: &[u8]) -> Carried { + let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d))); + if super::place::document::is_native(name, bytes) { + return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc))); + } + if super::place::document::is_pdf(name, bytes) { + // A PDF that can't be opened may carry editing data all the same. + return match vectorcraft_pdf::open_pdf(bytes, None) { + // Attachments left unsearched may list another editing file, which can't be checked. + Ok(opened) if opened.editing_search_cut() => Carried::Unreadable, + // An editing file listed whose data can't be resolved can't be checked either. + Ok(opened) => match opened.editing() { + Some(e) => read(&e.data), + None if opened.has_editing_file() => Carried::Unreadable, + None => Carried::Absent, + }, + Err(_) => Carried::Unreadable, + }; + } + if !vectorcraft_eps::has_native(bytes) { + return Carried::Absent; + } + vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data)) +} + +/// The error for a linked file the package would copy whose native document can't be read to +/// check the files and folders it names against the read roots. +const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots"; + /// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the -/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a -/// relative path taken from the file's folder): the copy would name it. +/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file +/// outside them (a relative path taken from the file's folder): the copy would name it. A file +/// whose native document can't be read is refused, as its links can't be checked. The error names +/// no file or folder. fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { if crate::file_access::current().is_none() { return Ok(()); } match carried_document(name, bytes) { - Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), - None => Ok(()), + Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), + Carried::Unreadable => Err(bad(C, UNREADABLE)), + Carried::Absent => Ok(()), } } @@ -150,7 +188,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { return Ok(()); } match carried_document(name, bytes) { - Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)), + Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => { + Err(bad(C, FOLDER_OUTSIDE)) + } + Carried::Unreadable => Err(bad(C, UNREADABLE)), _ => Ok(()), } } @@ -498,6 +539,9 @@ pub struct Package { root: Option, info: Option, doc: std::sync::Arc, + /// The read roots in force where the package was prepared: [`Package::write`] collects under + /// them. + scope: crate::file_access::ScopeHandle, } impl Session { @@ -544,21 +588,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?.doc.clone(); let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); - Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) + let scope = crate::file_access::ScopeHandle::capture(); + Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope }) } impl Package { /// Collect the linked files and fonts and write the package's files with `write` into /// `folder/name`, making its folders first, or into the zip without a folder → the reply of - /// `file.package`. + /// `file.package`, with the read roots in force where it was prepared, on any thread. pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - collect_and_write(self, write) + self.scope.clone().run(|| collect_and_write(self, write)) } } /// [`Package::write`]. fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package; + let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package; let mut doc = (*original).clone(); let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION); let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) }; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2421b71d77..fddd6cdd9c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters 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 (exceptions: docs/mcp.md)", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters 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 (exceptions: docs/mcp.md)", has_doc, default_paint ), @@ -274,8 +274,9 @@ impl DocState { /// Whether the selected objects' fills and strokes differ as the proxies show them (a "?" /// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item) /// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of - /// each selected object's own stack is compared. One walk of the document, so callers that ask - /// every frame cache it by revision. + /// each selected object's own stack is compared. The selected objects are found through the id + /// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk + /// of the document, so callers that ask every frame cache it by revision. pub fn proxy_mixed(&self, item: Option) -> (bool, bool) { self.proxy_mixed_with(item, &[]) } @@ -290,15 +291,17 @@ impl DocState { if self.selection.symbol_part.is_some() { return (false, false); } - let ids: std::collections::HashSet = self.selection.objects.iter().copied().collect(); - let (mut selected, mut nodes) = (vec![], vec![]); - self.doc.walk(|n| { - if ids.contains(&n.id) { - selected.push(n); - painted(n, true, &mut nodes); - } - }); + // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); + let (mut selected, mut nodes) = (vec![], vec![]); + // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each + // place it appears. + for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { + #[cfg(test)] + tests::note_gathered(); + selected.push(n); + painted(n, true, &mut nodes); + } let differ = |stroke: bool| { let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); let set = if item.is_some() { &selected } else { &nodes }; @@ -1035,6 +1038,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); + // A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object. + let style = super::newart::redefined_default_style(&before).cloned(); super::overprint::edit_counted(s, "Default Fill and Stroke", |d| { for id in &ids { let Some(n) = d.node_mut(*id) else { continue }; @@ -1045,7 +1050,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { r.style.stroke = Paint::None; } } - _ => n.appearance = Appearance::default_art().into(), + _ => { + n.appearance = match &style { + Some(g) => g.appearance_on(n).into_owned().into(), + None => Appearance::default_art().into(), + } + } } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); @@ -1316,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result { } s.execute("object.setProps", &Value::Object(q)) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs new file mode 100644 index 0000000000..3da5d73d9e --- /dev/null +++ b/crates/engine/src/cmd/paint/tests.rs @@ -0,0 +1,335 @@ +//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the +//! id cache: it answers as a walk of the whole document does, and with a few objects selected it +//! reads only those. + +use std::cell::Cell; +use std::collections::HashSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{painted, picked_colors, proxy_paint, same_in_proxy}; +use crate::{DocState, Session}; + +thread_local! { + /// [`gathered`] of this thread. + static GATHERED: Cell = const { Cell::new(0) }; +} + +/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones. +pub(super) fn note_gathered() { + GATHERED.set(GATHERED.get() + 1); +} + +/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones. +fn gathered() -> u64 { + GATHERED.get() +} + +/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document. +fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) -> (bool, bool) { + if st.selection.is_empty() { + return (false, false); + } + if st.selection.symbol_part.is_some() { + return (false, false); + } + let ids: HashSet = st.selection.objects.iter().copied().collect(); + let (mut selected, mut nodes) = (vec![], vec![]); + st.doc.walk(|n| { + if ids.contains(&n.id) { + selected.push(n); + painted(n, true, &mut nodes); + } + }); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); + let differ = |stroke: bool| { + let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); + let set = if item.is_some() { &selected } else { &nodes }; + let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) { + c if c.is_empty() => vec![proxy_paint(n, stroke, item)], + c => c.into_iter().map(Paint::solid).collect(), + }); + let Some(p0) = paints.next() else { return false }; + paints.any(|p| !same_in_proxy(&p0, &p)) + }; + (differ(false), differ(true)) +} + +/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item +/// and with and without `points`, with the id cache built and without it. +fn agree(st: &DocState, points: &[(NodeId, Vec)], what: &str) { + for cold in [true, false] { + if cold { + st.doc.drop_lookup_cache(); + } + for item in [None, Some(0), Some(1), Some(2), Some(3)] { + for points in [points, &[]] { + assert_eq!( + st.proxy_mixed_with(item, points), + walked(st, item, points), + "{what}: item {item:?}, {} picked points, cold cache {cold}", + points.len() + ); + } + } + } +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId { + let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap(); + id +} + +/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object, +/// different fills or strokes, a group with different contents, a group with one of its objects, +/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a +/// gradient mesh with points picked beside another object, ids not in the document and an id that +/// appears twice (a damaged file) with different paints. +#[test] +fn the_question_marks_match_a_walk_of_the_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let a = rect(&mut s, 10.0, "#ff0000", "#000000"); + let b = rect(&mut s, 40.0, "#0000ff", "#000000"); + let c = rect(&mut s, 70.0, "#ff0000", "#00ff00"); + // Two fills: [Fill, Stroke, Fill]. + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap(); + let e = rect(&mut s, 100.0, "#ff0000", "#000000"); + let f = rect(&mut s, 130.0, "#00ff00", "#000000"); + let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap()); + let mesh = rect(&mut s, 160.0, "#ff0000", "#000000"); + s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap(); + let hidden = rect(&mut s, 190.0, "#0000ff", "#000000"); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let h = rect(&mut s, 220.0, "#ff0000", "#000000"); + let missing = NodeId(999_999); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") }; + let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1)); + s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap(); + let points = vec![(mesh, vec![p00, p01])]; + let points_alike = vec![(mesh, vec![p01, p11])]; + + let selections = [ + vec![a], + vec![a, b], + vec![b, a], + vec![a, h], + vec![g], + vec![g, e], + vec![e, g], + vec![f, e], + vec![c], + vec![c, a], + vec![a, c], + vec![mesh], + vec![mesh, a], + vec![a, mesh, h], + vec![hidden], + vec![hidden, b], + vec![missing], + vec![missing, a], + vec![a, missing, b], + vec![a, a], + ]; + let check = |s: &mut Session, what: &str| { + for sel in &selections { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + agree(st, &points, &format!("{what}: {sel:?}")); + agree(st, &points_alike, &format!("{what}: {sel:?}, alike points")); + } + s.execute("select.all", &json!({})).unwrap(); + agree(s.active().unwrap(), &points, &format!("{what}: Select All")); + }; + check(&mut s, "unique ids"); + + // A second node with a's id and another fill, at the end of the tree. + let st = s.active_mut().unwrap(); + let mut copy = st.doc.node(a).unwrap().clone(); + copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let doc = Arc::make_mut(&mut st.doc); + let last = doc.layers.len() - 1; + Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy)); + doc.drop_lookup_cache(); + check(&mut s, "a repeated id"); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![a]; + assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill"); +} + +/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other +/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order. +fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec) { + let mut d = Document::new(612.0, 792.0); + d.layers.clear(); + let mut rects = vec![]; + for l in 0..layers { + let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0)); + for _ in 0..groups { + let children = (0..per_group) + .map(|_| { + let id = d.alloc_id(); + let mut ap = Appearance::default_art(); + let red = rects.len() % 2 == 0; + ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) })); + rects.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap)) + }) + .collect(); + let group = Node::group(d.alloc_id(), children); + layer.children_mut().unwrap().push(Arc::new(group)); + } + d.layers.push(Arc::new(layer)); + } + (d, rects) +} + +fn state(doc: Document) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap(); + s.active_mut().unwrap().doc = Arc::new(doc); + s +} + +/// With one object selected, the "?" reads only that object, not every node of the document, and +/// does not walk the tree once the id cache is built; with every object selected it walks the tree +/// once. +#[test] +fn the_question_marks_read_only_the_selected_objects() { + let (doc, rects) = big(2, 40, 25); + let mut s = state(doc); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![rects[777]]; + assert_eq!(st.proxy_mixed(None), (false, false)); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (false, false)); + assert_eq!(gathered() - read, 1, "only the selected object is read"); + assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers"); + + st.selection.objects = vec![rects[3], rects[1500]]; + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0)); + + st.selection.objects = rects.clone(); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!(gathered() - read, rects.len() as u64); + assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection"); +} + +/// Random selections of a document with nested groups answer as a walk does. +#[test] +fn random_selections_match_a_walk_of_the_document() { + let (doc, rects) = big(3, 12, 6); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let layers: Vec = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + let all: Vec = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect(); + let mut r = 0x2545_f491_4f6c_dd1d_u64; + let mut next = |n: usize| { + r ^= r << 13; + r ^= r >> 7; + r ^= r << 17; + (r % n as u64) as usize + }; + for round in 0..200 { + let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 }); + let sel: Vec = (0..count).map(|_| all[next(all.len())]).collect(); + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}")); + } +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on +/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn proxy_mixed_timing() { + let (doc, rects) = big(5, 100, 100); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let cases: [(&str, Vec); 5] = [ + ("1 object", vec![rects[25_000]]), + ("2 objects, different fills", vec![rects[10], rects[40_001]]), + ("a group of 100", vec![groups[250]]), + ("all 500 groups", groups.clone()), + ("all 50,000 objects", rects.clone()), + ]; + const CALLS: usize = 200; + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |"); + println!("|---|---|---|---|---|"); + for (name, sel) in &cases { + for cold in [false, true] { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}"); + let (mut old, mut new) = (vec![], vec![]); + let calls = if cold { CALLS / 10 } else { CALLS }; + for _ in 0..7 { + for (times, use_walk) in [(&mut old, true), (&mut new, false)] { + let d = time(|| { + for _ in 0..calls { + if cold { + st.doc.drop_lookup_cache(); + } + std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) }); + } + }); + times.push(d.as_secs_f64() * 1e6 / calls as f64); + } + } + let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::>().join(" "); + println!( + "| {name} | {} | {:.1} | {:.1} | {} / {} |", + if cold { "dropped before each call" } else { "built" }, + median(old.clone()), + median(new.clone()), + runs(&old), + runs(&new) + ); + } + } +} diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 3ee7117dbb..8e7d7f7b0f 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -36,6 +36,9 @@ //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` //! themselves ([`check_effect_color`], [`check_effect_channel`]). +use std::collections::HashMap; +use std::sync::OnceLock; + use serde_json::Value; use vectorcraft_apischema::shown_key; @@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command}; use crate::Result; /// What a params description says about the keys of the params object. -#[derive(Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct ParamKeys<'a> { /// The keys it names. pub keys: Vec<&'a str>, @@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool { /// The keys a params description names, or what in it doesn't read as one. pub fn doc_keys(doc: &str) -> std::result::Result, String> { + #[cfg(test)] + PARSES.with(|n| n.set(n.get() + 1)); let mut out = ParamKeys::default(); let (mut body, mut rest) = object_body(doc)?; let mut entries = split_top(body, ','); @@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator Option> { - let parsed = doc_keys(doc).ok()?; + resolve(doc, depth, &mut |doc| doc_keys(doc).ok()) +} + +/// [`accepted`], with `parse` reading each description it reaches. +fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option>) -> Option> { + let parsed = parse(doc)?; let mut keys = parsed.keys; for more in parsed.more { let mut named = named_commands(more).peekable(); @@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option> { if UNCHECKED.contains(&spec.id) { return None; } - keys.extend(accepted(spec.params, depth + 1)?); + keys.extend(resolve(spec.params, depth + 1, parse)?); } } Some(keys) } +/// What the params description of a built-in command says about its keys, read once per process +/// ([`known`]). +#[derive(Debug)] +struct Known { + /// The keys it names itself; none when it doesn't parse. + own: Vec<&'static str>, + /// [`accepted`] of it. + accepted: Option>, + /// [`id_stands_for_ids`] of it. + id_stands_for_ids: bool, +} + +impl Known { + /// [`takes_key`] of the description. + fn takes(&self, key: &str) -> bool { + self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key)) + } +} + +/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's) +/// has another place. +fn text_key(doc: &str) -> (usize, usize) { + (doc.as_ptr().addr(), doc.len()) +} + +/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once. +/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose +/// keys change as plug-ins are installed and removed. +fn read_descriptions(docs: impl IntoIterator) -> HashMap<(usize, usize), Known> { + let names_plugin = + |more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX)); + let mut parsed: HashMap<(usize, usize), (Option>, bool)> = HashMap::new(); + let mut table = HashMap::new(); + for doc in docs { + if table.contains_key(&text_key(doc)) { + continue; + } + let mut live = false; + let mut parse = |doc: &'static str| { + let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| { + let keys = doc_keys(doc).ok(); + let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m))); + (keys, plugin) + }); + live |= *plugin; + keys.clone() + }; + let own = parse(doc).map(|p| p.keys).unwrap_or_default(); + let accepted = resolve(doc, 0, &mut parse); + if live { + continue; + } + let mut known = Known { own, accepted, id_stands_for_ids: false }; + known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc); + table.insert(text_key(doc), known); + } + table +} + +/// [`Known`] of `doc` when it is the params description of a built-in command. +fn known(doc: &str) -> Option<&'static Known> { + #[cfg(test)] + if UNCACHED.get() { + return None; + } + static TABLE: OnceLock> = OnceLock::new(); + TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc)) +} + +#[cfg(test)] +thread_local! { + /// The times [`doc_keys`] parsed a description on this thread. + pub(crate) static PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether [`known`] is skipped on this thread ([`uncached`]). + static UNCACHED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether [`read_descriptions`] keeps what `doc` says. +#[cfg(test)] +pub(crate) fn read_once(doc: &'static str) -> bool { + read_descriptions([doc]).contains_key(&text_key(doc)) +} + +/// `f`'s result with every description parsed again where it is used, as without [`known`]. +#[cfg(test)] +pub(crate) fn uncached(f: impl FnOnce() -> T) -> T { + let before = UNCACHED.replace(true); + let out = f(); + UNCACHED.set(before); + out +} + /// Every key the description `doc` takes, those of the commands its `…` entries name included, or /// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a /// command in [`UNCHECKED`]. pub(crate) fn accepted_keys(doc: &'static str) -> Option> { - accepted(doc, 0) + match known(doc) { + Some(known) => known.accepted.clone(), + None => accepted(doc, 0), + } } /// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands /// its `…` entries name)? pub fn takes_key(doc: &'static str, key: &str) -> bool { + if let Some(known) = known(doc) { + return known.takes(key); + } doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key)) } @@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool { /// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names /// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)? pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool { + if let Some(known) = known(doc) { + return known.id_stands_for_ids; + } + takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc) +} + +/// No params object of `doc` names `ids` beside a required `id`. +fn no_required_id_beside_ids(doc: &str) -> bool { fn head(alternative: &str) -> &str { alternative.split([':', '=', '(']).next().unwrap_or_default().trim() } - if !takes_key(doc, "ids") || !takes_key(doc, "id") { - return false; - } let mut rest = doc; while let Ok((body, after)) = object_body(rest) { let entries = split_top(body, ','); @@ -249,9 +362,17 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { if given.is_empty() { return Ok(()); } - let Some(keys) = accepted(doc, 0) else { return Ok(()) }; + let live; + let keys = match known(doc) { + Some(known) => known.accepted.as_deref(), + None => { + live = accepted(doc, 0); + live.as_deref() + } + }; + let Some(keys) = keys else { return Ok(()) }; match given.keys().find(|k| !keys.contains(&k.as_str())) { - Some(key) => Err(unknown(id, key, &keys)), + Some(key) => Err(unknown(id, key, keys)), None => Ok(()), } } @@ -261,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"), ]; @@ -933,9 +1055,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { crate::schemas::check(spec, params, false)?; } if matches!(id, "command.batch" | "action.batch") && !in_batch { - for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() { + for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() { if let Some(step_id) = step.get("command").and_then(Value::as_str) { - check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?; + let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true); + // An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do. + match checked { + Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))), + checked => checked?, + } } } } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 6c06b52c6c..f2a1b1d9f7 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1,10 +1,10 @@ //! Path editing commands (used by the Pen and Direct Selection tools and Object → Path). -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection}; +use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection}; use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2}; use super::create::anchor_from_json; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Move Anchors", [], None, - "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", + "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", has_selection, move_anchors ), @@ -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 ), @@ -245,28 +245,43 @@ fn close(s: &mut Session, p: &Value) -> Result { pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result { let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?); - check_switches(p, &["patterns"], "path.moveAnchors")?; + check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?; // An object selected in a symbol instance's art stays where the symbol puts it. super::edit::refuse_symbol_part(s)?; // Objects selected whole move as objects, and their pattern tiles move with them when // `patterns` (default: General › Transform Pattern Tiles) is on. let whole = s.doc()?.selection.whole(); let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() }; - transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc)?; + let interpolate = interpolates_handles(s, p, "path.moveAnchors")?; + transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?; // Transform Again repeats a move that moved something; a drag records it when it commits. let st = s.doc_mut()?; if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) { - let options = json!({ "copy": false, "patterns": sc.patterns }); + let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate }); st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options)); st.last_perspective = None; } ok() } +/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the +/// segments beside them (`interpolate` param, else General › Interpolate Control Points When +/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference +/// is then. A saved step without `interpolate` ([`Session::replay`]) was recorded before the +/// preference existed, so it moves the handles as it did then, without re-mapping them. +pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Result { + let default = s.prefs.interpolate_control_points && !s.replaying(); + let on = switch_or(p, "interpolate", default, cmd)?; + s.note_journal("interpolate", json!(on)); + Ok(on) +} + /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the /// objects selected whole (those with no entry in the selection's `anchors`). An object inside /// another selected object, such as a path in a selected group, moves once, with that object. -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling) -> Result<()> { +/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end +/// are re-mapped ([`move_interpolating_handles`]). +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { let sel = s.doc()?.selection.clone(); let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone()); let c = xf.as_coeffs(); @@ -277,9 +292,15 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge match sel.anchors.get(id) { Some(set) => { let path = path_mut(doc, *id)?; - for &(si, ai) in set { - if let Some(a) = path.anchor_mut(si, ai) { - *a = a.transform(xf); + // Only an exact move takes the interpolating path: a near-identity scale or + // turn still transforms the anchors as asked. + if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] { + move_interpolating_handles(path, set, delta); + } else { + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + *a = a.transform(xf); + } } } // A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps @@ -307,12 +328,138 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge }) } +/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles +/// of each segment with exactly one moved end by the map that takes the segment's old ends to its +/// new ends: a turn, a uniform scale and a move. Between two corner anchors the segment keeps its +/// shape relative to its ends. A segment with both ends moved, or with its ends at the same place +/// before or after the move, moves as it does without the preference. A smooth anchor keeps its +/// two handles in line ([`line_up_handles`]). +fn move_interpolating_handles(path: &mut PathData, set: &BTreeSet, d: Vec2) { + // (subpath, anchor, outgoing handle?, new position) + let mut placed: Vec<(usize, usize, bool, Point)> = Vec::new(); + if d != Vec2::ZERO { + // Only the segments beside a moved anchor can have one moved end: (subpath, first anchor). + let mut segments: BTreeSet = BTreeSet::new(); + for &(si, ai) in set { + let Some(sp) = path.subpaths.get(si) else { continue }; + let n = sp.anchors.len(); + if ai >= n || n < 2 { + continue; + } + if ai > 0 || sp.closed { + segments.insert((si, (ai + n - 1) % n)); + } + if ai + 1 < n || sp.closed { + segments.insert((si, ai)); + } + } + for (si, from) in segments { + let Some(sp) = path.subpaths.get(si) else { continue }; + let to = (from + 1) % sp.anchors.len().max(1); + let (moved_from, moved_to) = (set.contains(&(si, from)), set.contains(&(si, to))); + if moved_from == moved_to { + continue; + } + let (Some(a), Some(b)) = (sp.anchors.get(from), sp.anchors.get(to)) else { continue }; + let old = b.p - a.p; + let len2 = old.hypot2(); + if len2 <= 1e-12 || !len2.is_finite() { + continue; + } + let start = if moved_from { a.p + d } else { a.p }; + let end = if moved_to { b.p + d } else { b.p }; + let new = end - start; + // A move that puts the two ends at the same place would collapse both handles onto + // them, past recovering by moving back. + if new.hypot2() <= 1e-12 { + continue; + } + // `new / old` as complex numbers: the turn and scale between the two chords. + let (re, im) = ((new.x * old.x + new.y * old.y) / len2, (new.y * old.x - new.x * old.y) / len2); + let map = |h: Point| { + let v = h - a.p; + start + Vec2::new(v.x * re - v.y * im, v.x * im + v.y * re) + }; + // A retracted handle goes to its anchor's new place exactly: mapped, it could land a + // rounding error away, which `line_up_handles` would read as a direction. + let h_out = if a.h_out == a.p { start } else { map(a.h_out) }; + let h_in = if b.h_in == b.p { end } else { map(b.h_in) }; + if h_out.is_finite() && h_in.is_finite() { + placed.push((si, from, true, h_out)); + placed.push((si, to, false, h_in)); + } + } + } + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + a.translate(d); + } + } + // For each anchor with a re-mapped handle: its handles as the plain move left them, and which + // of them (outgoing, incoming) were re-mapped. + let mut touched: BTreeMap = BTreeMap::new(); + for &(si, ai, out, pos) in &placed { + if let Some(a) = path.anchor_mut(si, ai) { + let e = touched.entry((si, ai)).or_insert((a.h_out, a.h_in, false, false)); + if out { + a.h_out = pos; + e.2 = true; + } else { + a.h_in = pos; + e.3 = true; + } + } + } + for ((si, ai), (rigid_out, rigid_in, out, inn)) in touched { + let Some(a) = path.anchor_mut(si, ai) else { continue }; + if a.kind == AnchorKind::Smooth && !line_up_handles(a, out, inn) { + a.h_out = rigid_out; + a.h_in = rigid_in; + } + } +} + +/// Put the handles of the smooth anchor `a` back in line after [`move_interpolating_handles`] +/// re-mapped its outgoing handle (`out`), its incoming handle (`inn`) or both. A re-mapped handle +/// turns to point away from the other handle, at its own new length; when both were re-mapped, +/// both point along the mean of their directions. A retracted handle is left as it is. False when +/// both were re-mapped to point the same way, which has no mean direction: the caller then moves +/// both handles with the anchor. +fn line_up_handles(a: &mut Anchor, out: bool, inn: bool) -> bool { + let (v_out, v_in) = (a.h_out - a.p, a.h_in - a.p); + let (l_out, l_in) = (v_out.hypot(), v_in.hypot()); + if l_out <= 0.0 || l_in <= 0.0 || !l_out.is_finite() || !l_in.is_finite() { + return true; + } + let dir = match (out, inn) { + (true, true) => v_out / l_out - v_in / l_in, + (true, false) => -v_in / l_in, + (false, true) => v_out / l_out, + (false, false) => return true, + }; + let l = dir.hypot(); + if l <= 1e-12 || !l.is_finite() { + return false; + } + let dir = dir / l; + if out { + a.h_out = a.p + dir * l_out; + } + if inn { + a.h_in = a.p - dir * l_in; + } + true +} + fn set_handle(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?; let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0); 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 @@ -332,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.rs b/crates/engine/src/cmd/place.rs index 486a5633a7..5106bb1148 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -1152,6 +1152,13 @@ pub fn read_info(p: &Value) -> Result { Ok(out) } +/// Resolution at a placed image's transform: 72 points per inch over each pixel axis. +pub(super) fn effective_ppi(xf: Affine) -> [f64; 2] { + let [a, b, c, d, ..] = xf.as_coeffs(); + let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l); + [ppi(a, b), ppi(c, d)] +} + pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { const C: &str = "image.info"; let st = s.doc()?; @@ -1165,9 +1172,6 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { let doc = super::links::with_brush_art(&st.doc); let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; - // Effective resolution: 72 pt per inch over the points one pixel spans along each axis. - let [a, b, c, d, ..] = im.xf.as_coeffs(); - let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l); let size = n.geometric_bounds().unwrap_or_default(); // A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info. let doc_path = super::links::LinkBase::of(st).doc; @@ -1179,7 +1183,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { "colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)), "pixelWidth": im.width, "pixelHeight": im.height, - "ppi": [ppi(a, b), ppi(c, d)], + "ppi": effective_ppi(im.xf), "width": size.width(), "height": size.height(), })) 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/place/text.rs b/crates/engine/src/cmd/place/text.rs index 7d8afc92d4..78261a8804 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -3,8 +3,8 @@ use serde_json::Value; -use super::super::utf16_order_without_mark; -use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param}; +use super::super::{text_param, utf16_order_without_mark}; +use super::{Point, Rect, Result, bad, fileio, shapes, switch_or}; /// Text files as `file.place` reports them (not a format `document.open` reads). pub(super) const FORMAT: fileio::Format = fileio::Format { @@ -22,13 +22,68 @@ pub(super) const FORMAT: fileio::Format = fileio::Format { /// document may give. pub(super) const MAX_TEXT: usize = 4 << 20; +/// A character set of Text Import Options (`text.characterSet`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum CharacterSet { + /// UTF-8, or UTF-16 with or without a byte-order mark ([`decode`]). + #[default] + Unicode, + /// The platform's 8-bit character set: Windows-1252, or Mac Roman on a Mac. + Ansi, + ShiftJis, + Gb2312, + ChineseBig5, + Cyrillic, + Gb18030, + Greek, + Turkish, + Baltic, + CentralEuropean, +} + +/// Each character set by its `text.characterSet` value. +const CHARACTER_SETS: [(&str, CharacterSet); 11] = [ + ("unicode", CharacterSet::Unicode), + ("ansi", CharacterSet::Ansi), + ("shiftJis", CharacterSet::ShiftJis), + ("gb2312", CharacterSet::Gb2312), + ("chineseBig5", CharacterSet::ChineseBig5), + ("cyrillic", CharacterSet::Cyrillic), + ("gb18030", CharacterSet::Gb18030), + ("greek", CharacterSet::Greek), + ("turkish", CharacterSet::Turkish), + ("baltic", CharacterSet::Baltic), + ("centralEuropean", CharacterSet::CentralEuropean), +]; + +impl CharacterSet { + /// The Encoding Standard decoder of a set other than Unicode and ANSI, for a file from a Mac + /// when `mac`: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic on a Mac), and + /// Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both + /// platforms. + fn encoding(self, mac: bool) -> Option<&'static encoding_rs::Encoding> { + Some(match self { + Self::Unicode | Self::Ansi => return None, + Self::ShiftJis => encoding_rs::SHIFT_JIS, + Self::Gb2312 => encoding_rs::GBK, + Self::ChineseBig5 => encoding_rs::BIG5, + Self::Cyrillic if mac => encoding_rs::X_MAC_CYRILLIC, + Self::Cyrillic => encoding_rs::WINDOWS_1251, + Self::Gb18030 => encoding_rs::GB18030, + Self::Greek => encoding_rs::WINDOWS_1253, + Self::Turkish => encoding_rs::WINDOWS_1254, + Self::Baltic => encoding_rs::WINDOWS_1257, + Self::CentralEuropean => encoding_rs::WINDOWS_1250, + }) + } +} + /// Text Import Options (`file.place`'s `text` param). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct TextOptions { - /// Decode as the platform's 8-bit character set (Windows-1252 or Mac Roman) instead of - /// Unicode. - ansi: bool, - /// The file comes from a Mac (its 8-bit character set is Mac Roman). + /// The character set the file's bytes are decoded as. + character_set: CharacterSet, + /// The file comes from a Mac (its ANSI set is Mac Roman, its Cyrillic set x-mac-cyrillic). mac: bool, /// Join the lines of each block of text (blank lines end paragraphs). remove_line_returns: bool, @@ -45,11 +100,13 @@ impl TextOptions { if !t.is_object() { return Err(bad(cmd, "text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?}")); } - let choice = |key: &str, values: [&str; 2]| match str_param(t, key) { - None => Ok(false), - Some(v) if v == values[0] => Ok(false), - Some(v) if v == values[1] => Ok(true), - Some(v) => Err(bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", values[0], values[1]))), + // The index of `text[key]` in `values`; 0 when it is omitted or null. + let choice = |key: &str, values: &[&str]| -> Result { + let Some(v) = text_param(t, key, cmd)? else { return Ok(0) }; + values.iter().position(|x| *x == v).ok_or_else(|| { + let (last, rest) = values.split_last().map_or(("", &[][..]), |(last, rest)| (*last, rest)); + bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", rest.join("\", \""), last)) + }) }; let spaces_to_tab = match t.get("replaceSpaces") { None | Some(Value::Null) => None, @@ -58,11 +115,12 @@ impl TextOptions { as usize, ), }; + let set = choice("characterSet", &CHARACTER_SETS.map(|(name, _)| name))?; Ok(Self { - ansi: choice("characterSet", ["unicode", "ansi"])?, - mac: choice("platform", ["windows", "mac"])?, - remove_line_returns: bool_or(t, "removeLineReturns", false), - remove_paragraph_returns: bool_or(t, "removeParagraphReturns", false), + character_set: CHARACTER_SETS.get(set).map_or(CharacterSet::Unicode, |(_, s)| *s), + mac: choice("platform", &["windows", "mac"])? == 1, + remove_line_returns: switch_or(t, "removeLineReturns", false, cmd)?, + remove_paragraph_returns: switch_or(t, "removeParagraphReturns", false, cmd)?, spaces_to_tab, }) } @@ -80,10 +138,15 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result /// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the /// file has an even length, reads as valid UTF-16 with no NUL character in the byte order /// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit -/// set), or the platform's 8-bit character set. +/// set), the platform's 8-bit character set, or another set's decoder +/// ([`CharacterSet::encoding`]), which reads a byte-order mark as ordinary bytes and a malformed +/// sequence as U+FFFD. fn decode(bytes: &[u8], o: TextOptions) -> String { + if let Some(encoding) = o.character_set.encoding(o.mac) { + return encoding.decode_without_bom_handling(bytes).0.into_owned(); + } let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() }; - if o.ansi { + if o.character_set == CharacterSet::Ansi { return eight_bit(bytes); } let utf16 = |rest: &[u8], le: bool| { @@ -278,22 +341,76 @@ mod tests { assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, 0xE9, 0], unicode), "hé", "UTF-16 LE"); assert_eq!(decode(&[0xFE, 0xFF, 0, b'h', 0x20, 0xAC], unicode), "h€", "UTF-16 BE"); assert_eq!(decode(&[b'c', b'a', b'f', 0xE9, 0x80], unicode), "café€", "not UTF-8: Windows-1252"); - let ansi = TextOptions { ansi: true, ..TextOptions::default() }; + let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() }; assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é"); - let mac = TextOptions { ansi: true, mac: true, ..TextOptions::default() }; + let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() }; assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€"); } + /// The other character sets decode by their Encoding Standard decoders: the platform matters + /// for Cyrillic alone, a byte-order mark is read as ordinary bytes, and a malformed sequence + /// reads as U+FFFD. + #[test] + fn decodes_the_other_character_sets() { + let cases: [(CharacterSet, &[u8], &str); 9] = [ + (CharacterSet::ShiftJis, &[0x93, 0xFA, 0x96, 0x7B], "日本"), + (CharacterSet::Gb2312, &[0xD6, 0xD0, 0xCE, 0xC4], "中文"), + (CharacterSet::ChineseBig5, &[0xA4, 0xA4, 0xA4, 0xE5], "中文"), + (CharacterSet::Cyrillic, &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + (CharacterSet::Gb18030, &[0x95, 0x32, 0x82, 0x36], "\u{20000}"), + (CharacterSet::Greek, &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"), + (CharacterSet::Turkish, &[0xDD, 0x73, 0x74], "İst"), + (CharacterSet::Baltic, &[0x52, 0xEE, 0x67, 0x61], "Rīga"), + (CharacterSet::CentralEuropean, &[0xA3, 0xF3, 0x64, 0x9F], "Łódź"), + ]; + for (set, bytes, text) in cases { + let windows = TextOptions { character_set: set, ..TextOptions::default() }; + assert_eq!(decode(bytes, windows), text, "{set:?}"); + if set != CharacterSet::Cyrillic { + assert_eq!(decode(bytes, TextOptions { mac: true, ..windows }), text, "{set:?} from a Mac"); + } + } + let mac_cyrillic = TextOptions { character_set: CharacterSet::Cyrillic, mac: true, ..TextOptions::default() }; + assert_eq!(decode(&[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], mac_cyrillic), "Привет"); + let shift_jis = TextOptions { character_set: CharacterSet::ShiftJis, ..TextOptions::default() }; + assert_eq!(decode(&[0x82, 0x22], shift_jis), "\u{FFFD}\"", "a lead byte before ASCII"); + assert_eq!(decode(&[b'a', 0x82], shift_jis), "a\u{FFFD}", "a lead byte at the end"); + let central = TextOptions { character_set: CharacterSet::CentralEuropean, ..TextOptions::default() }; + assert_eq!(decode(&[0xEF, 0xBB, 0xBF, b'A'], central), "A", "a UTF-8 byte-order mark is read as windows-1250"); + assert_eq!(decode(&[0xFF, 0xFE, b'A', 0], shift_jis), "\u{FFFD}\u{FFFD}A\0", "a UTF-16 byte-order mark is read as Shift JIS"); + } + #[test] fn options_parse_and_reject_bad_values() { let p = serde_json::json!({"text": {"characterSet": "ansi", "platform": "mac", "removeLineReturns": true, "replaceSpaces": 4}}); let o = TextOptions::parse(&p, "file.place").unwrap(); - assert_eq!(o, TextOptions { ansi: true, mac: true, remove_line_returns: true, remove_paragraph_returns: false, spaces_to_tab: Some(4) }); + assert_eq!( + o, + TextOptions { + character_set: CharacterSet::Ansi, + mac: true, + remove_line_returns: true, + remove_paragraph_returns: false, + spaces_to_tab: Some(4) + } + ); + for (name, set) in CHARACTER_SETS { + let o = TextOptions::parse(&serde_json::json!({"text": {"characterSet": name}}), "file.place").unwrap(); + assert_eq!(o.character_set, set, "{name}"); + } assert_eq!(TextOptions::parse(&serde_json::json!({}), "file.place").unwrap(), TextOptions::default()); - for bad in - [serde_json::json!({"text": 3}), serde_json::json!({"text": {"platform": "amiga"}}), serde_json::json!({"text": {"replaceSpaces": 1}})] - { + for bad in [ + serde_json::json!({"text": 3}), + serde_json::json!({"text": {"platform": "amiga"}}), + serde_json::json!({"text": {"replaceSpaces": 1}}), + serde_json::json!({"text": {"characterSet": 3}}), + serde_json::json!({"text": {"platform": true}}), + serde_json::json!({"text": {"removeLineReturns": "yes"}}), + serde_json::json!({"text": {"removeParagraphReturns": 1}}), + ] { assert!(TextOptions::parse(&bad, "file.place").is_err(), "{bad}"); } + let null = serde_json::json!({"text": {"characterSet": null, "platform": null, "removeLineReturns": null}}); + assert_eq!(TextOptions::parse(&null, "file.place").unwrap(), TextOptions::default(), "null leaves the default"); } } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 48a6649d77..5570dc6a81 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -161,6 +161,8 @@ pub struct FilterRun { parent: Option, /// The document it was made from, and that document's revision then. document: (u64, u64), + /// The plug-in's limits with the Plug-in Instruction Budget in force when it was made. + limits: vectorcraft_plugins::Limits, } /// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run @@ -245,7 +247,11 @@ impl FilterRun { let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len()); let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?; let document = (st.uid, st.revision); - Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document }) + let limits = match s.prefs.plugin_instruction_budget { + crate::PluginBudget::Normal => plugin.limits().clone(), + crate::PluginBudget::Large => plugin.large_limits(), + }; + Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits }) } /// The plug-in, for its name and budget. @@ -274,7 +280,13 @@ impl FilterRun { /// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between /// two slices of its budget. pub fn run(&self) -> Result> { - self.plugin.run(&self.input, &self.params).map_err(err) + self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err) + } + + /// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when + /// it was made. + pub fn limits(&self) -> &vectorcraft_plugins::Limits { + &self.limits } /// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the @@ -289,7 +301,7 @@ impl FilterRun { let may = self.plugin.manifest().permissions(); let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite)); let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args); - self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err) + self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err) } /// Runs a plug-in that calls commands and applies its output: the calls and the output are one diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 6c23161a9d..867c1f2ff0 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -64,6 +64,7 @@ const DENIED_PREFIXES: &[&str] = &[ "edit.newDocument", "edit.colorSettings", "edit.dropSelection", + "symbol.placeFromDocument", "artboard.copy", "artboard.cut", "text.rescanFonts", diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 9ea619e366..5a10ae3d9c 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -41,10 +41,12 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.image.removeBackground", "addon.image.removeColorMask", "addon.packaging.check", + "addon.packaging.fold", "addon.packaging.roles", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", + "addon.pathtools.bridge", "addon.pathtools.close", "addon.pathtools.commonTangents", "addon.pathtools.corner", @@ -86,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", @@ -175,6 +178,7 @@ pub(super) const ALLOWED: &[&str] = &[ "edit.duplicate", "edit.findNext", "edit.findReplace", + "edit.replaceMatch", "effect.apply", "effect.deferredStatus", "effect.duplicate", @@ -553,6 +557,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.update", "shape.arc", "shape.circleThroughPoints", + "shape.editFlare", "shape.ellipse", "shape.flare", "shape.line", @@ -687,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/preflight.rs b/crates/engine/src/cmd/preflight.rs new file mode 100644 index 0000000000..ebfaf5deeb --- /dev/null +++ b/crates/engine/src/cmd/preflight.rs @@ -0,0 +1,133 @@ +//! Production preflight: the existing output-aware type walk, linked-file probes and image +//! resolution calculation, returned as findings that the interface can locate and recheck. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_text::{FontDb, FontMatch}; + +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, number_or, text_param}; + +const COMMAND: &str = "document.preflight"; +const KINDS: [&str; 4] = ["fonts", "text", "links", "resolution"]; + +pub fn specs() -> Vec { + vec![cmd!( + query "document.preflight", + "Production Preflight", + [], + None, + "{output?: pdf|print|screen (pdf), minPpi?: 1..9600 (300, or 96 for screen), artboards?: [index, …] (0-based whole numbers; default all)} check the selected output without writing files or editing the document; print reuses the saved print settings with these artboards, pdf and screen check visible artwork on these artboards. Reuses output-aware font and overflow checks, Links file status and image.info effective resolution. Resource findings locate their first visible canvas owner; resolution inside resource art is reported as not checked because its placed scale can differ. → {output, minPpi, artboards, checks: [{kind: fonts|text|links|resolution, status: passed|failed|notChecked, count, notChecked}], findings: [{kind, code, ids (canvas objects), name, detail?, sourceId?, effectivePpi?, threshold?}], outputWarnings, limitations}; a pass covers only these checks, not certification of a produced file", + has_doc, + check + )] +} + +fn check(s: &mut Session, p: &Value) -> Result { + let output = text_param(p, "output", COMMAND)?.unwrap_or("pdf"); + if !matches!(output, "pdf" | "print" | "screen") { + return Err(bad(COMMAND, "output must be pdf, print or screen")); + } + let min_ppi = number_or(p, "minPpi", if output == "screen" { 96.0 } else { 300.0 }, COMMAND)?; + if !min_ppi.is_finite() || !(1.0..=9600.0).contains(&min_ppi) { + return Err(bad(COMMAND, "minPpi must be from 1 to 9600")); + } + let indices = match p.get("artboards").filter(|v| !v.is_null()) { + Some(v) => super::panelcmds::listed_artboards(&s.doc()?.doc, v, "artboards", COMMAND)?, + None => (0..s.doc()?.doc.artboards.len()).collect(), + }; + let context = if output == "print" { + super::print::preflight_context(s, &indices)? + } else { + let doc = &s.doc()?.doc; + let pages = indices.iter().filter_map(|i| doc.artboards.get(*i).map(|a| (a.rect, vectorcraft_geom::Affine::IDENTITY))).collect(); + super::print::PreflightContext { layers: vectorcraft_pdf::PrintLayers::Visible, pages, warnings: vec![] } + }; + let areas = context.pages.iter().map(|(r, _)| *r).collect::>(); + let st = s.doc()?; + let doc = st.doc.with_placed_art(); + let mut layers = doc.layers.clone(); + vectorcraft_pdf::keep_layers(&mut layers, context.layers); + let typed = super::fonts::preflight_type(&doc, &layers, &areas); + let statuses = super::links::statuses(st); + let mut findings = vec![]; + let db = FontDb::global(); + for (font, ids) in typed.fonts { + let code = match db.resolve(&font.0, &font.1).map(|(_, m)| m) { + None | Some(FontMatch::Missing) => "missingFont", + Some(FontMatch::Style) => "substitutedFont", + _ => continue, + }; + findings.push( + json!({ "kind": "fonts", "code": code, "ids": ids.iter().map(|i| i.0).collect::>(), "name": super::fonts::font_label(&font) }), + ); + } + for id in typed.overflow { + findings.push(finding("text", "overflow", id, &doc)); + } + let mut resolution_unchecked = 0usize; + for (source, owner) in typed.images { + if let Some((status, _, _)) = statuses.get(&source) { + let code = match status.as_str() { + "missing" => Some("missingLink"), + "modified" => Some("modifiedLink"), + _ => None, + }; + if let Some(code) = code { + let mut f = finding("links", code, owner, &doc); + f["sourceId"] = json!(source.0); + findings.push(f); + } + } + // A vector placed document has no single bitmap resolution. Its embedded artwork, and + // resources with their own coordinate systems, must never be certified at a local scale. + if doc.node(source).is_none() || source != owner { + resolution_unchecked += 1; + continue; + } + let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node(source).map(|n| &n.kind) else { + resolution_unchecked += 1; + continue; + }; + let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n)); + let ppi = context + .pages + .iter() + .filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0)) + .map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf)) + .reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]); + let Some(ppi) = ppi else { + resolution_unchecked += 1; + continue; + }; + // Inverting the placed-size transform can round an exact threshold slightly down. + if ppi.iter().any(|n| !n.is_finite() || *n <= 0.0) { + resolution_unchecked += 1; + } else if ppi.iter().any(|n| *n < min_ppi * (1.0 - 1e-9)) { + let mut f = finding("resolution", "lowResolution", owner, &doc); + f["effectivePpi"] = json!(ppi); + f["threshold"] = json!(min_ppi); + findings.push(f); + } + } + let checks = KINDS.map(|kind| { + let count = findings.iter().filter(|f| f["kind"] == kind).count(); + let not_checked = if kind == "resolution" { resolution_unchecked } else { 0 }; + let status = if count > 0 { + "failed" + } else if not_checked > 0 { + "notChecked" + } else { + "passed" + }; + json!({ "kind": kind, "status": status, "count": count, "notChecked": not_checked }) + }); + Ok(json!({ + "output": output, "minPpi": min_ppi, "artboards": indices, "checks": checks, + "findings": findings, "outputWarnings": context.warnings, + "limitations": ["These checks do not certify an exported file.", "Resolution inside symbols, patterns, brushes, opacity masks and placed documents is not checked."] + })) +} + +fn finding(kind: &str, code: &str, id: NodeId, doc: &vectorcraft_doc::Document) -> Value { + json!({ "kind": kind, "code": code, "ids": [id.0], "name": doc.node(id).map(|n| n.display_name()).unwrap_or_else(|| id.0.to_string()) }) +} diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index ab116007b3..dd5d5c1628 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -139,6 +139,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("cornerRadius", "General", "", "Corner Radius", len(0.0, 1296.0, General)), p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)), p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool), + p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool), p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool), p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), @@ -157,6 +158,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")), @@ -324,6 +327,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text), // Plug-ins & Scratch Disks p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text), + // The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input. + p!( + "pluginInstructionBudget", + "Plug-ins & Scratch Disks", + "Plug-ins", + "Plug-in Instruction Budget", + choice(&[("normal", "Normal"), ("large", "Large")]) + ), p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text), p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text), // User Interface diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 0826e848cf..8c507db007 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result { Ok(v) } +/// Reuse the Print dialog's saved settings and page geometry for production preflight, without +/// printing, writing a file or duplicating its type warnings. +pub(super) struct PreflightContext { + pub layers: PrintLayers, + pub pages: Vec<(Rect, Affine)>, + pub warnings: Vec, +} + +pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result { + let settings = + json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::>().join(",") } }); + let set = preset_or_saved("document.preflight", s, &s.doc()?.doc, &settings)?; + super::printadvanced::flattener("document.preflight", &set, &s.prefs.flattener_presets)?; + let mut pv = vectorcraft_pdf::preview(&s.doc()?.doc, &set).map_err(|e| pdf_error("document.preflight", e))?; + let pages = pv + .sheets + .iter() + .filter_map(|p| { + let to_page = Affine::new(p.transform); + on_page(Rect::new(p.area[0], p.area[1], p.area[2], p.area[3]), to_page, (p.width, p.height)).map(|area| (area, to_page)) + }) + .collect(); + pv.warnings.extend(pv.setting_notes); + Ok(PreflightContext { layers: set.print_layers, pages, warnings: pv.warnings }) +} + /// The parts of the document (document space) that the pages of `pv` print. fn areas(pv: &PrintPreview) -> Vec { pv.sheets 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/select.rs b/crates/engine/src/cmd/select.rs index ea3181faf9..b7a6043a98 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -375,6 +375,59 @@ fn is_selectable_within(d: &Document, iso: Option, locks: Option<&Locked } } +/// The object Next Object Above (`dir` > 0) or Next Object Below selects from `cur`: the nearest +/// sibling of `cur` in that direction that [`walk_selectable`] visits. Hidden and locked objects +/// and sublayers are passed over. Only the siblings are read, not the rest of the document. +fn step_target(d: &Document, iso: Option, cur: NodeId, dir: i64) -> Option { + let path = d.index_path(cur)?; + let (&idx, up) = path.split_last()?; + // The objects that hold `cur` and its siblings, from the top-level layer down. + let mut holders = Vec::with_capacity(up.len()); + let mut siblings = &d.layers; + for &i in up { + let n = siblings.get(i)?; + holders.push(n.as_ref()); + siblings = n.children()?; + } + let iso = iso.and_then(|i| d.node(i)); + let locks = d.locked_artboards(); + let visits = |n: &Node| walk_visits(&holders, n, iso, &locks); + let next = if dir > 0 { siblings.iter().skip(idx + 1).find(|n| visits(n)) } else { siblings.iter().take(idx).rev().find(|n| visits(n)) }; + next.map(|n| n.id) +} + +/// Whether [`walk_selectable`] visits `n`, read from the objects that hold it: `holders` are its +/// layer and the sublayers, groups and other containers inside it that hold `n`, outermost first +/// (its [`Document::ancestry`] without `n`). `iso` is the isolated object. Unlike +/// [`is_selectable`], it passes over sublayers and the ruler guides of a layer, which the walk +/// looks through or leaves out. +fn walk_visits(holders: &[&Node], n: &Node, iso: Option<&Node>, locks: &LockedArtboards) -> bool { + let len = holders.len() + 1; + let at = |i: usize| holders.get(i).copied().unwrap_or(n); + let open = |i: usize| at(i).visible && !at(i).locked; + let start = match iso { + Some(c) => { + let Some(p) = (0..len).find(|&i| at(i).id == c.id) else { return false }; + if !(0..=p).all(|i| open(i) && !at(i).is_template()) { + return false; + } + // A single object isolated is all there is to select. + if !c.is_container() { + return p + 1 == len; + } + p + 1 + } + None => 0, + }; + // The object Select All takes: the first one that is not a layer, inside visible, unlocked + // layers and sublayers that are not template layers. + let Some(top) = (start..len).find(|&i| !at(i).is_layer()) else { return false }; + (start..top).all(|i| open(i) && !at(i).is_template()) + && !at(top).is_ruler_guide() + && (top..len).all(open) + && (iso.is_some() || locks.is_empty() || !locks.holds(at(top))) +} + /// The first selected object, in selection order, that [`is_selectable`] accepts. pub(crate) fn first_selectable(st: &DocState) -> Option<&Node> { let locks = st.doc.locked_artboards(); @@ -475,17 +528,7 @@ fn inverse(s: &mut Session, _: &Value) -> Result { fn step(s: &mut Session, dir: i64) -> Result { let st = s.doc()?; let Some(cur) = st.selection.objects.first().copied() else { return ok() }; - let Some((par, idx, _)) = st.doc.position(cur) else { return ok() }; - let Some(siblings) = st.doc.children(par) else { return ok() }; - // The nearest sibling in that direction that `walk_selectable` visits: hidden and locked - // objects and sublayers are passed over. - let can = selectable_ids(&st.doc, st.isolation); - let next = if dir > 0 { - siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id)) - } else { - siblings.iter().take(idx).rev().find(|n| can.contains(&n.id)) - }; - let Some(id) = next.map(|n| n.id) else { return ok() }; + let Some(id) = step_target(&st.doc, st.isolation, cur, dir) else { return ok() }; s.select(|_, sel| sel.set([id]))?; ok() } @@ -1399,5 +1442,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result { #[cfg(test)] mod same_tests; +#[cfg(test)] +mod step_tests; + #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/select/step_tests.rs b/crates/engine/src/cmd/select/step_tests.rs new file mode 100644 index 0000000000..0a43cc0cf0 --- /dev/null +++ b/crates/engine/src/cmd/select/step_tests.rs @@ -0,0 +1,347 @@ +//! Select > Next Object Above and Below through [`step_target`], which reads only the siblings of +//! the selected object, against a copy of the search that collected every object +//! [`walk_selectable`] visits on each step. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use serde_json::json; +use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{selectable_ids, step_target, walk_visits}; +use crate::Session; + +/// The search as it was before it read only the siblings: the nearest sibling in that direction +/// that `walk_selectable` visits, from the set of every object it visits. +fn step_base(d: &Document, iso: Option, cur: NodeId, dir: i64) -> Option { + let (par, idx, _) = d.position(cur)?; + let siblings = d.children(par)?; + let can = selectable_ids(d, iso); + let next = if dir > 0 { + siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id)) + } else { + siblings.iter().take(idx).rev().find(|n| can.contains(&n.id)) + }; + next.map(|n| n.id) +} + +/// A small xorshift generator, so that each seed gives the same document every run. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + /// True `pct` times in 100. + fn chance(&mut self, pct: u64) -> bool { + self.below(100) < pct + } +} + +fn rect_node(d: &mut Document, x: f64, y: f64) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 40.0)), Appearance::default()) +} + +fn layer_node(d: &mut Document, children: Vec) -> Node { + let mut l = Node::layer(d.alloc_id(), "Layer", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + ch.extend(children.into_iter().map(Arc::new)); + } + l +} + +fn ruler_guide(d: &mut Document, pos: f64) -> Node { + Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: pos > 300.0, pos, artboard: None }) +} + +/// Up to six objects: rectangles on and off the artboard, guides made from paths, ruler guides, +/// groups, and sublayers, some hidden, locked or template layers. Groups and sublayers hold more +/// below `depth`. Sublayers and ruler guides also go inside groups, which the app does not make, +/// so that every shape of tree is compared. +fn objects(r: &mut Rng, d: &mut Document, depth: u32) -> Vec { + (0..r.below(7)) + .map(|_| { + let (x, y) = (r.below(1400) as f64 - 300.0, r.below(1000) as f64 - 200.0); + let mut n = match r.below(if depth == 0 { 6 } else { 10 }) { + 0..=3 => rect_node(d, x, y), + 4 => { + let mut n = rect_node(d, x, y); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + n + } + 5 => ruler_guide(d, x), + 6 | 7 => { + let kids = objects(r, d, depth - 1); + Node::group(d.alloc_id(), kids.into_iter().map(Arc::new).collect()) + } + _ => { + let kids = objects(r, d, depth - 1); + layer_node(d, kids) + } + }; + n.visible = !r.chance(10); + n.locked = r.chance(10); + if let NodeKind::Layer { template, .. } = &mut n.kind { + *template = r.chance(15); + } + n + }) + .collect() +} + +/// A document of one to three layers, some hidden, locked or template layers, holding +/// [`objects`], with its artboard locked in some seeds. +fn random_document(seed: u64) -> Document { + let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let mut d = Document::new(800.0, 600.0); + let layers = (0..1 + r.below(3)) + .map(|_| { + let kids = objects(&mut r, &mut d, 3); + let mut l = layer_node(&mut d, kids); + l.visible = !r.chance(10); + l.locked = r.chance(10); + if let NodeKind::Layer { template, .. } = &mut l.kind { + *template = r.chance(10); + } + Arc::new(l) + }) + .collect(); + d.layers = layers; + if let Some(a) = d.artboards.first_mut() { + a.locked = r.chance(40); + } + d +} + +/// Every node of `d`, layers included, in tree order. +fn all_ids(d: &Document) -> Vec { + let mut ids = vec![]; + d.walk(|n| ids.push(n.id)); + ids +} + +/// The objects that hold `id`, outermost first, and the node itself. +fn holders(d: &Document, id: NodeId) -> (Vec<&Node>, &Node) { + let a = d.ancestry(id).unwrap(); + let (last, up) = a.split_last().unwrap(); + (up.iter().map(|i| d.node(*i).unwrap()).collect(), d.node(*last).unwrap()) +} + +/// For every node of random documents, outside isolation mode and with each of several nodes +/// isolated, `walk_visits` says what the set of the objects `walk_selectable` visits says, and +/// Next Object Above and Below from it give what the search over that set gave. +#[test] +fn next_object_gives_what_the_search_over_every_selectable_object_gave() { + let (mut steps, mut moved, mut isolated) = (0, 0, 0); + for seed in 0..300 { + let d = random_document(seed); + let ids = all_ids(&d); + let mut r = Rng(seed + 7); + let mut isos = vec![None]; + isos.extend((0..10).map(|_| Some(ids[r.below(ids.len() as u64) as usize]))); + let locks = d.locked_artboards(); + for iso in isos { + let can = selectable_ids(&d, iso); + let iso_node = iso.and_then(|i| d.node(i)); + for &id in &ids { + let (up, n) = holders(&d, id); + assert_eq!(walk_visits(&up, n, iso_node, &locks), can.contains(&id), "seed {seed}, isolating {iso:?}, node {id:?}"); + } + for &cur in &ids { + for dir in [1, -1] { + let want = step_base(&d, iso, cur, dir); + assert_eq!(step_target(&d, iso, cur, dir), want, "seed {seed}, isolating {iso:?}, from {cur:?}, direction {dir}"); + steps += 1; + moved += usize::from(want.is_some()); + isolated += usize::from(want.is_some() && iso.is_some()); + } + } + } + } + // The documents give many steps that select something, inside isolation mode too. + eprintln!("{moved} of {steps} steps select an object, {isolated} of them in isolation mode"); + assert!(moved > 5_000, "{moved} of {steps} steps select an object"); + assert!(isolated > 500, "{isolated} steps select an object in isolation mode"); +} + +/// A session holding `d`, with `iso` isolated and `cur` selected. +fn session(d: Document, iso: Option, cur: NodeId) -> Session { + let mut s = Session::new(); + s.add_document(d, None); + let st = s.doc_mut().unwrap(); + st.isolation = iso; + st.selection.set([cur]); + s +} + +fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.to_vec() +} + +/// In an isolated layer, Next Object Above and Below pass over a sublayer beside the selected object, +/// as the walk looks through it. +#[test] +fn next_object_passes_over_a_sublayer_in_an_isolated_layer() { + let mut d = Document::new(800.0, 600.0); + let a = rect_node(&mut d, 0.0, 0.0); + let inner = rect_node(&mut d, 100.0, 0.0); + let b = rect_node(&mut d, 200.0, 0.0); + let sub = layer_node(&mut d, vec![inner]); + let (a_id, b_id) = (a.id, b.id); + let l = layer_node(&mut d, vec![a, sub, b]); + let layer = l.id; + d.layers = vec![Arc::new(l)]; + assert_eq!(step_base(&d, Some(layer), a_id, 1), Some(b_id)); + let mut s = session(d, Some(layer), a_id); + s.execute("select.nextAbove", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![b_id]); + s.execute("select.nextBelow", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![a_id]); +} + +/// Next Object Above passes over a ruler guide of the layer, which the walk leaves out, unless the +/// guide is the object isolated. +#[test] +fn next_object_passes_over_a_ruler_guide_of_the_layer() { + let mut d = Document::new(800.0, 600.0); + let a = rect_node(&mut d, 0.0, 0.0); + let b = rect_node(&mut d, 200.0, 0.0); + let guide = ruler_guide(&mut d, 100.0); + let (a_id, b_id, guide_id) = (a.id, b.id, guide.id); + let l = layer_node(&mut d, vec![a, b, guide]); + d.layers = vec![Arc::new(l)]; + // Nothing above the rectangle but the guide: the selection stays. + assert_eq!(step_base(&d, None, b_id, 1), None); + let mut s = session(d.clone(), None, b_id); + s.execute("select.nextAbove", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![b_id]); + s.execute("select.nextBelow", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![a_id]); + // The guide isolated on its own is what there is to select. + assert_eq!(step_base(&d, Some(guide_id), b_id, 1), Some(guide_id)); + assert_eq!(step_target(&d, Some(guide_id), b_id, 1), Some(guide_id)); +} + +/// The first selected object anchors the search even when it can no longer be selected itself. +#[test] +fn next_object_steps_from_a_hidden_first_selected_object() { + let mut d = Document::new(800.0, 600.0); + let mut a = rect_node(&mut d, 0.0, 0.0); + a.visible = false; + let b = rect_node(&mut d, 200.0, 0.0); + let (a_id, b_id) = (a.id, b.id); + let l = layer_node(&mut d, vec![a, b]); + d.layers = vec![Arc::new(l)]; + assert_eq!(step_base(&d, None, a_id, 1), Some(b_id)); + let mut s = session(d, None, a_id); + s.execute("select.nextAbove", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![b_id]); +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = Instant::now(); + f(); + start.elapsed() + } + } +} + +/// A document of `groups` groups of `per` rectangles on one layer, or of `per` rectangles when +/// `groups` is 0 → the document and the object in the middle of the layer. +fn wide(groups: usize, per: usize) -> (Document, NodeId) { + let mut d = Document::new(800.0, 600.0); + let mut top = vec![]; + if groups == 0 { + top.extend((0..per).map(|i| rect_node(&mut d, (i % 200) as f64 * 4.0, (i / 200 % 150) as f64 * 4.0))); + } else { + for g in 0..groups { + let kids: Vec> = (0..per).map(|i| Arc::new(rect_node(&mut d, (i % 20) as f64 * 4.0, (g % 150) as f64 * 4.0))).collect(); + top.push(Node::group(d.alloc_id(), kids)); + } + } + let mid = top[top.len() / 2].id; + let l = layer_node(&mut d, top); + d.layers = vec![Arc::new(l)]; + (d, mid) +} + +/// A search for the object Next Object Above or Below selects: [`step_base`] or [`step_target`]. +type Step = fn(&Document, Option, NodeId, i64) -> Option; + +/// Timings of Next Object Above and Below, stepping up and down from the object in the middle of +/// the layer, by the search over every selectable object (200 steps a run) and by the siblings +/// alone (200,000 steps a run, as one step takes too little time to measure), on 100,000 +/// rectangles and on 1,000 groups of 100, run in turn on the same document, 7 runs each. Ignored by +/// default; it prints the median, fastest and slowest time per step and sets no bound on them: +/// `cargo test --release -p vectorcraft-engine --lib next_object_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn next_object_perf() { + const RUNS: usize = 7; + const OLD_STEPS: usize = 200; + const NEW_STEPS: usize = 200_000; + let per_step = |d: Duration, steps: usize| d.as_secs_f64() * 1e6 / steps as f64; + eprintln!("next_object_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!("next_object_perf: {:<26} {:>32} {:>32}", "document", "every object µs/step (min-max)", "siblings µs/step (min-max)"); + for (name, groups, per) in [("100,000 rectangles", 0, 100_000), ("1,000 groups of 100", 1_000, 100)] { + let (d, mid) = wide(groups, per); + let walk = |f: Step, steps: usize| { + let mut cur = mid; + let mut seen = Vec::with_capacity(steps); + for i in 0..steps { + cur = f(&d, None, cur, if i % 2 == 0 { 1 } else { -1 }).unwrap_or(cur); + seen.push(cur); + } + std::hint::black_box(seen) + }; + let (mut old, mut new) = (Vec::new(), Vec::new()); + let (mut a, mut b) = (vec![], vec![]); + for run in 0..RUNS { + // The two take turns going first. + if run % 2 == 0 { + old.push(time(|| a = walk(step_base, OLD_STEPS))); + new.push(time(|| b = walk(step_target, NEW_STEPS))); + } else { + new.push(time(|| b = walk(step_target, NEW_STEPS))); + old.push(time(|| a = walk(step_base, OLD_STEPS))); + } + assert_eq!(a[..], b[..OLD_STEPS], "{name}"); + assert_ne!(a[0], mid, "{name}: the first step selects another object"); + } + old.sort(); + new.sort(); + eprintln!( + "next_object_perf: {name:<26} {:>12.3} ({:>8.3}-{:>9.3}) {:>12.3} ({:>8.3}-{:>9.3})", + per_step(old[RUNS / 2], OLD_STEPS), + per_step(old[0], OLD_STEPS), + per_step(old[RUNS - 1], OLD_STEPS), + per_step(new[RUNS / 2], NEW_STEPS), + per_step(new[0], NEW_STEPS), + per_step(new[RUNS - 1], NEW_STEPS), + ); + } +} diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 667e674d17..d1f147ffbe 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -220,8 +220,10 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result, Vec<_>) = picked.into_iter().partition(own); + // A leaf already listed is skipped; a set keeps this linear in the number of leaves. + let mut seen: std::collections::HashSet = out.iter().copied().collect(); for id in super::leaf_targets(s, &rest)? { - if !out.contains(&id) { + if seen.insert(id) { out.push(id); } } @@ -429,6 +431,52 @@ impl Session { painted(first, true, &mut nodes); node_stroke(nodes.first()?) } + + /// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush + /// ([`vectorcraft_brush::keeps_brush_size`])? If they do, a width profile changes none of + /// them, and the result is `Some`, holding whether any of them has a width profile. The result + /// is `None` when a profile changes at least one of them. + /// + /// The strokes are the ones `stroke.set` edits: + /// - the Appearance panel's active stroke row in each target that has an equal row + /// ([`ItemTarget::per_target`]), and the top stroke in the others; + /// - else a selected group's own stroke; + /// - else the top strokes of the objects it paints ([`own_stroke_or_leaves`]). + /// + /// The art of graph designs is left out, and so are images and symbol instances without an + /// active row. The result is also `None` with nothing selected, with an object inside a symbol + /// instance selected, with type among the targets while no Appearance row is active for it, + /// and with a target that has no stroke row, since `stroke.set` gives such a target a plain + /// stroke. + pub fn brushed_strokes_profiled(&self) -> Option { + const C: &str = "stroke.set"; + let st = self.active()?; + if st.selected_symbol_part().is_some() { + return None; + } + let p = json!({}); + let item = item_target(self, &p, C).ok()?.of_kind(self, false); + let ids = if item == ItemTarget::Top { own_stroke_or_leaves(self, &p).ok()? } else { item.targets(self, &p).ok()? }; + let mut ids = super::appearance::drop_design_art_rows(self, ids, item, false, C).ok()?; + if item == ItemTarget::Top { + ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. }))); + } + let mut strokes = vec![]; + for (id, each) in ids.iter().zip(item.per_target(self, &ids)) { + let n = st.doc.node(*id)?; + let row = each?.resolve(&n.appearance, false, C).ok()?; + if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { + return None; + } + strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?); + } + if strokes.is_empty() { + return None; + } + // The library is read only when every stroke names a brush. + let lib = vectorcraft_brush::library(&st.doc); + strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + } } impl DocState { @@ -678,6 +726,7 @@ fn profile_list(s: &mut Session, _: &Value) -> Result { #[cfg(test)] mod tests { use super::*; + use vectorcraft_doc::NodeId; #[test] fn weight_steps_follow_units_and_stop_at_their_bounds() { @@ -693,4 +742,93 @@ mod tests { assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9); assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9); } + + fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) + } + + fn made(v: Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}"))) + } + + /// The targets of [`own_stroke_or_leaves`] merged by a linear search of the growing list. + fn listed_merge(s: &Session, p: &Value) -> Vec { + let d = &s.doc().unwrap().doc; + let own = |id: &NodeId| { + d.node(*id).is_some_and(|n| { + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some() + }) + }; + let (mut out, rest): (Vec<_>, Vec<_>) = super::super::targets(s, p).unwrap().into_iter().partition(own); + for id in super::super::leaf_targets(s, &rest).unwrap() { + if !out.contains(&id) { + out.push(id); + } + } + out + } + + /// `stroke.set` with no `item` lists the same targets in the same order as a linear merge: + /// groups and layers with a stroke of their own (repeats kept), the leaves of plain groups and + /// layers, compound paths and compound shapes for their members, and each leaf once, also + /// when it is named both directly and through its group. + #[test] + fn stroke_targets_match_the_listed_merge() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 2000, "height": 400})); + let base = s.doc().unwrap().doc.layers[0].id; + let mut x = 0.0; + let mut rect = |s: &mut Session| { + x += 120.0; + made(run(s, "shape.rectangle", json!({"x": x, "y": 100, "width": 100, "height": 100}))) + }; + let (a, b) = (rect(&mut s), rect(&mut s)); + let plain = made(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))); + let (c, d) = (rect(&mut s), rect(&mut s)); + let owned = made(run(&mut s, "object.group", json!({"ids": [c.0, d.0]}))); + run(&mut s, "appearance.addStroke", json!({"ids": [owned.0]})); + let (e, f) = (rect(&mut s), rect(&mut s)); + run(&mut s, "select.set", json!({"ids": [e.0, f.0]})); + let compound = made(run(&mut s, "object.compoundPath.make", json!({}))); + let (g, h) = (rect(&mut s), rect(&mut s)); + run(&mut s, "select.set", json!({"ids": [g.0, h.0]})); + let shape = made(run(&mut s, "object.compoundShape.make", json!({}))); + let lone = rect(&mut s); + let layer = made(run(&mut s, "layer.new", json!({}))); + let (j, k) = (rect(&mut s), rect(&mut s)); + run(&mut s, "appearance.addStroke", json!({"ids": [layer.0]})); + { + let doc = &s.doc().unwrap().doc; + assert_eq!((doc.parent_of(j), doc.parent_of(k)), (Some(layer), Some(layer)), "the new layer holds the last two"); + assert_eq!((doc.parent_of(e), doc.parent_of(g)), (Some(compound), Some(shape))); + assert!(doc.node(owned).unwrap().appearance.stroke().is_some() && doc.node(layer).unwrap().appearance.stroke().is_some()); + } + let named = json!({"ids": [plain.0, a.0, owned.0, owned.0, c.0, e.0, compound.0, g.0, lone.0, layer.0, j.0]}); + let cases = [ + named.clone(), + json!({"ids": [j.0, h.0, f.0, b.0, plain.0, layer.0, owned.0, k.0, shape.0]}), + json!({"ids": [base.0, layer.0, base.0]}), + json!({"ids": [d.0, owned.0, base.0]}), + json!({"ids": []}), + ]; + for p in &cases { + assert_eq!(own_stroke_or_leaves(&s, p).unwrap(), listed_merge(&s, p), "{p}"); + } + run(&mut s, "select.set", json!({"ids": [lone.0, owned.0, f.0, plain.0, b.0, layer.0]})); + assert_eq!(own_stroke_or_leaves(&s, &json!({})).unwrap(), listed_merge(&s, &json!({})), "the selection"); + + // The edit reaches every listed target, counting a repeated one once, and leaves the other + // member of the group with its own stroke alone. + let want = listed_merge(&s, &named); + assert_eq!(want.iter().filter(|id| **id == owned).count(), 2, "{want:?}"); + let distinct: std::collections::HashSet<_> = want.iter().collect(); + let before = s.doc().unwrap().doc.node(d).unwrap().clone(); + let r = run(&mut s, "stroke.set", json!({"ids": named["ids"], "weight": 3})); + let doc = &s.doc().unwrap().doc; + assert_eq!(r["objects"], distinct.len(), "{r} {want:?}"); + for id in &want { + assert_eq!(doc.node(*id).unwrap().appearance.stroke().map(|st| st.width), Some(3.0), "{id:?}"); + } + assert_eq!(doc.node(d), Some(&before), "a member reached only through its group's own stroke is left alone"); + } } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 33c9ec67bb..1b5fec0a3b 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", + "{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", has_doc, style_redefine ), @@ -318,8 +318,14 @@ impl Session { /// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands /// for the topmost path directly inside it, which a style applied to the group links. pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> { + self.graphic_style_of(*self.active()?.selection.subjects().first()?) + } + + /// The graphic style of object `id` of the active document, as [`Self::selection_graphic_style`] + /// gives it for the first selected object. + pub fn graphic_style_of(&self, id: NodeId) -> Option<(&GraphicStyle, bool)> { let st = self.active()?; - let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?); + let n = super::appearance::look_holder(&st.doc, st.doc.node(id)?); let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?; Some((g, in_sync(n, g))) } @@ -483,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value { fn style_redefine(s: &mut Session, p: &Value) -> Result { let cmd = "graphicStyle.redefine"; - let (src, n) = source(s, p, cmd)?; - let d = &s.doc()?.doc; - // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. - let n = super::appearance::look_holder(d, n); - let src = if n.id == src { src } else { n.id }; - let i = match str_param(p, "name") { - Some(name) => style_index(d, name)?, - None => n - .extras() - .graphic_style - .and_then(|id| d.graphic_style_by_id(id)) - .and_then(|g| d.graphic_style_index(&g.name)) - .ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?, + // The style to replace, its new look, and the object that look comes from (none for another style's look). + let (i, look, src) = match p.get("from") { + Some(from) => { + let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?; + if p.get("id").is_some() { + return Err(bad(cmd, "pass `id` or `from`, not both")); + } + let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?; + let d = &s.doc()?.doc; + let (i, j) = (style_index(d, name)?, style_index(d, from)?); + // A style dropped on itself, or on a style with the same look, stays as it is. + let target = &d.graphic_styles[i]; + let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() }; + if i == j || look == *target { + return Ok(json!({ "name": name })); + } + (i, look, None) + } + None => { + let (src, n) = source(s, p, cmd)?; + let d = &s.doc()?.doc; + // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. + let n = super::appearance::look_holder(d, n); + let src = if n.id == src { src } else { n.id }; + let i = match str_param(p, "name") { + Some(name) => style_index(d, name)?, + None => n + .extras() + .graphic_style + .and_then(|id| d.graphic_style_by_id(id)) + .and_then(|g| d.graphic_style_index(&g.name)) + .ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?, + }; + (i, GraphicStyle::of(String::new(), captured(n), n), Some(src)) + } }; - let look = GraphicStyle::of(String::new(), captured(n), n); - let name = d.graphic_styles[i].name.clone(); + let name = s.doc()?.doc.graphic_styles[i].name.clone(); let chars = s.prefs.override_char_color; let before = s.doc()?.doc.clone(); s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| { @@ -507,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the // source or as a linked object: the graph draws it again from the design. - let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src); + let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); let (follow, edited): (Vec, Vec) = linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); set_link(d, &edited, None); @@ -515,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { // goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look. let mut follow_marks = super::graph::series_group_marks(d, &follow); let edited: HashSet = edited.into_iter().collect(); - follow_marks.retain(|nid| *nid != src && !edited.contains(nid)); + follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid)); super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); let g = d.graphic_styles[i].clone(); let mut shared = None; @@ -524,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { } super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); super::graph::capture_label_rows(d, &follow_marks); - let link = (!super::graph::is_design_art(d, src)).then_some(id); - set_link(d, &[src], link); + if let Some(src) = src { + let link = (!super::graph::is_design_art(d, src)).then_some(id); + set_link(d, &[src], link); + } Ok(()) })?; Ok(json!({ "name": name })) 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/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index 77266b5aaa..a413631bb3 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -314,12 +314,12 @@ pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<&SymbolEdit>) } } -/// Does `n` hold an instance of symbol `name`, directly or through the art of the symbols it holds -/// instances of? -fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet) -> bool { +/// Does `n` hold an instance of symbol `name` (opacity masks included), directly or through the art +/// of the symbols it holds instances of? +pub(crate) fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet) -> bool { let mut found = false; let mut nested = vec![]; - n.walk(&mut |c| { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| { if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { if symbol == name { found = true; diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index b82be77f43..3e4774a370 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -20,7 +20,7 @@ use super::clipboard::Clipboard; use super::clipboard::resources::SwatchChoices; use super::swatch::str_list; use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param, u64_req}; /// The extension of saved symbol libraries: native documents. pub const SYMBOLS_EXT: &str = vectorcraft_format::EXTENSION; @@ -54,6 +54,15 @@ pub fn specs() -> Vec { has_doc, add ), + cmd!( + "symbol.placeFromDocument", + "Place Symbol Instance", + [], + None, + "{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}", + has_doc, + place_from_document + ), cmd!( "symbol.saveLibrary", "Save Symbol Library…", @@ -630,6 +639,46 @@ fn add(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// `symbol.placeFromDocument`: an instance of symbol `name` of the open document `sourceDocument` +/// placed in the active document, with the symbol and the resources it uses added as a drop of +/// art from that document adds them, in one undo step. The source document is not changed. +fn place_from_document(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.placeFromDocument"; + let uid = u64_req(p, "sourceDocument", C)?; + let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?; + let st = s.doc()?; + let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?); + let parent = st.target_parent()?; + let same = uid == st.uid; + let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc)); + let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?; + if !src.symbols.iter().any(|sym| sym.name == name) { + return Err(bad(C, format!("no symbol named `{name}` in the document it came from"))); + } + // A symbol of the active document itself is placed as it is. + let clip = (!same).then(|| Clipboard::gather(&src, vec![instance(name)])); + // The source's colors are kept even where the active document has swatches of the same names. + let choices = SwatchChoices::parse(C, &json!({"swatchConflict": "add"}))?; + let (id, placed) = s.edit("Place Symbol Instance", |d, sel| { + let placed = match &clip { + // Each symbol added takes its Symbol Options along. + Some(clip) => { + let imported = clip.import_into(d, &choices, false)?; + let renamed = imported.renamed.iter().find(|r| r["kind"] == "symbol" && r["from"] == name).and_then(|r| r["to"].as_str()); + renamed.unwrap_or(name).to_string() + } + None => name.to_string(), + }; + let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed)); + let id = d.alloc_id(); + d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?; + sel.set([id]); + Ok((id, placed)) + })?; + Ok(json!({ "id": id.0, "name": placed })) +} + fn save(s: &mut Session, p: &Value) -> Result { const C: &str = "symbol.saveLibrary"; let st = s.doc()?; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index d544697c5c..11bd1b4259 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -522,14 +522,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option vectorcraft_color::Paint { +/// `[Normal Character Style]` in `d`: the defaults, with whatever a redefinition gave it (font, +/// size, fill…). New type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html): +/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html) +/// and [Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html): +/// new type's defaults, its font included, are changed by editing it), so it takes this style's +/// font and fill, not the current fill left from the last shape (#7975). Attributes that don't +/// pass its checks leave the defaults. +pub(crate) fn normal_char_style(d: &Document) -> CharStyle { let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default(); - with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill) + with_attrs(&CharStyle::default(), &normal, "text.create").unwrap_or_default() } /// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None` diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 82ac2f9f76..7e0d790568 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() { } } +/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the +/// thread as it was: every frame stays a frame of the thread with the text it holds, and the +/// symbol's art holds a copy of the text the frame shows. +#[test] +fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() { + for command in ["symbol.new", "symbol.update"] { + let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0); + let shown = frames.map(|id| text(&s, id)); + let name = if command == "symbol.update" { + let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap()); + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + "Mark" + } else { + "Story" + }; + s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap(); + let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap(); + assert!(r["id"].is_null(), "{command}: {r}"); + assert_eq!(threads(&s), [frames], "{command}: the thread is as it was"); + assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text"); + assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows"); + } +} + /// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the /// mask art too. #[test] 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/webexport.rs b/crates/engine/src/cmd/webexport.rs index c6764cddb4..498982a7f9 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Save for Web Preview", [], None, - "{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}", + "{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, shifted (by colorTable.shifted; also locked), webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}", has_doc, preview ), @@ -325,27 +325,60 @@ pub struct ColorTable { pub web_shift: Vec, #[serde(serialize_with = "ser_key", deserialize_with = "de_key")] pub sort: ColorSort, + /// Taken out of the table: their pixels take the nearest color left. A deleted color is no + /// longer locked, transparent or web-shifted. + pub deleted: Vec, + /// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the + /// table when the first color was deleted. Empty: the reduction makes the palette. + pub custom_palette: Vec, + /// Colors shifted by hand: each source color (`#rrggbb`) and the color it is written as. A + /// shifted color is locked, and a source the table does not hold shifts nothing. + pub shifted: std::collections::BTreeMap, } +/// A color shifted by hand: (source, color written). +type Shift = ([u8; 3], [u8; 3]); + /// The most colours a colour table list holds. const MAX_TABLE: usize = 256; +/// The error for a deletion that would leave the color table no color for the pixels. +pub const KEEP_ONE: &str = "colorTable.deleted: at least one color has to stay in the color table"; + impl ColorTable { + /// Whether the table is a Custom one: a color was deleted or the palette is fixed. + pub fn is_custom(&self) -> bool { + !self.deleted.is_empty() || !self.custom_palette.is_empty() + } + fn colors(list: &[String], what: &str) -> std::result::Result, String> { if list.len() > MAX_TABLE { return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours")); } - list.iter() - .map(|h| { - vectorcraft_color::Color::from_hex(h) - .filter(|_| !super::hex_with_alpha(h)) - .map(|c| { - let [r, g, b, _] = c.to_rgba8(1.0); - [r, g, b] - }) - .ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\"")) - }) - .collect() + list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect() + } + + /// The colors shifted by hand as (source, color written). An error names a value that is not a + /// color such as `#ff8800`, two keys that name one color, or more than 256 entries. + fn shifts(&self) -> std::result::Result, String> { + // One entry past the limit is enough for `colors` to refuse a longer map. + let (keys, values): (Vec, Vec) = self.shifted.iter().take(MAX_TABLE + 1).map(|(k, v)| (k.clone(), v.clone())).unzip(); + let sources = Self::colors(&keys, "shifted")?; + let to = Self::colors(&values, "shifted")?; + for (i, (s, k)) in sources.iter().zip(&keys).enumerate() { + if sources[..i].contains(s) { + return Err(format!("colorTable.shifted: `{k}` names a color another key names")); + } + } + Ok(sources.into_iter().zip(to).collect()) + } + + /// `h` as RGB; `None` when it is not a color such as `#ff8800`. + fn rgb(h: &str) -> Option<[u8; 3]> { + vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] + }) } } @@ -445,7 +478,13 @@ impl WebSettings { } } } - let s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?; + let mut s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?; + // Another reduction makes a new palette: the deletions and the fixed palette go, unless + // the params give the color table too. + if p.get("reduction").is_some() && p.get("colorTable").is_none() && s.reduction != self.reduction { + s.color_table.deleted.clear(); + s.color_table.custom_palette.clear(); + } s.checked() } @@ -463,11 +502,24 @@ impl WebSettings { return Err("width and height are at least 1 pixel".into()); } self.matte_rgb()?; + let table = &mut self.color_table; for (list, what) in - [(&self.color_table.locked, "locked"), (&self.color_table.transparent, "transparent"), (&self.color_table.web_shift, "webShift")] + [(&table.locked, "locked"), (&table.transparent, "transparent"), (&table.web_shift, "webShift"), (&table.custom_palette, "customPalette")] { ColorTable::colors(list, what)?; } + // A deleted color is no longer locked, transparent, web-shifted or shifted. + let deleted = ColorTable::colors(&table.deleted, "deleted")?; + if !deleted.is_empty() { + for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] { + list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c))); + } + } + // Shifts are kept as `#rrggbb` in lowercase; a color shifted to itself is not shifted, and + // a color shifted by hand is not web-shifted. + let shifts: Vec = table.shifts()?.into_iter().filter(|(s, to)| s != to && !deleted.contains(s)).collect(); + table.web_shift.retain(|h| ColorTable::rgb(h).is_none_or(|c| !shifts.iter().any(|(s, _)| *s == c))); + table.shifted = shifts.into_iter().map(|(s, to)| (hex(s), hex(to))).collect(); Ok(self) } @@ -614,6 +666,8 @@ pub struct TableColor { pub transparent: bool, pub locked: bool, pub web_shifted: bool, + /// Shifted by hand (`colorTable.shifted`): written as `color` instead of `source`. + pub shifted: bool, } /// An optimised image file. @@ -733,6 +787,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 let locked = ColorTable::colors(&table.locked, "locked")?; let to_clear = ColorTable::colors(&table.transparent, "transparent")?; let shift = ColorTable::colors(&table.web_shift, "webShift")?; + let by_hand = table.shifts()?; + let shifted_to = |src: &[u8; 3]| by_hand.iter().find(|(s, _)| s == src).map(|(_, to)| *to); + // A color shifted by hand is kept when the colors are reduced, as a locked one is, and takes + // one of the slots kept for them before the locked colors do. + let kept: Vec<[u8; 3]> = by_hand.iter().map(|(s, _)| *s).chain(locked.iter().copied()).collect(); let o = PaletteOptions { colors: s.colors, reduction: s.reduction, @@ -741,7 +800,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 transparency: s.transparency, matte, }; - let mut ix = quantize::quantize_locked(rgba, w, h, &o, &locked); + let mut ix = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. let before = ix.palette.clone(); let clear = ix.transparent.map(usize::from); @@ -755,11 +814,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 *slot = *c; } } - // Web snap, then the colours shifted by hand (locked colours stay as they are). + // Web shift and web snap (locked colors and colors shifted by hand stay as they are). let clear = ix.transparent.map(usize::from); for (i, c) in ix.palette.iter_mut().enumerate() { let src = sources.get(i).copied().unwrap_or(*c); - if Some(i) == clear || locked.contains(&src) { + if Some(i) == clear || shifted_to(&src).is_some() || locked.contains(&src) { continue; } if shift.contains(&src) { @@ -768,8 +827,19 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 *c = snapped; } } + // Lossy compares the pixels with the colors written for them, and moves no pixel into or out of + // a color shifted by hand. if s.format == WebFormat::Gif { - web::lossy(&mut ix, rgba, s.lossy); + let fixed: Vec = sources.iter().enumerate().filter(|(_, c)| shifted_to(c).is_some()).filter_map(|(i, _)| u8::try_from(i).ok()).collect(); + web::lossy(&mut ix, rgba, s.lossy, &fixed); + } + // The colors shifted by hand. + for (i, c) in ix.palette.iter_mut().enumerate() { + if Some(i) != clear + && let Some(to) = sources.get(i).and_then(shifted_to) + { + *c = to; + } } let order = web::sort(&mut ix, table.sort); let sources: Vec<[u8; 3]> = order.iter().map(|&i| sources.get(i).copied().unwrap_or_default()).collect(); @@ -778,17 +848,121 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 .iter() .zip(&sources) .enumerate() - .map(|(i, (c, src))| TableColor { - color: *c, - source: *src, - transparent: ix.transparent == u8::try_from(i).ok(), - locked: locked.contains(src), - web_shifted: shift.contains(src), + .map(|(i, (c, src))| { + let transparent = ix.transparent == u8::try_from(i).ok(); + let shifted = !transparent && shifted_to(src).is_some(); + TableColor { + color: *c, + source: *src, + transparent, + locked: locked.contains(src) || shifted, + web_shifted: shift.contains(src) && !shifted, + shifted, + } }) .collect(); Ok(PaletteImage { ix, colors, mapped }) } +/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the +/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the +/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to +/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of +/// `colors` together, and its first opaque colors that fit in the rest. +fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result { + let table = &s.color_table; + let deleted = ColorTable::colors(&table.deleted, "deleted")?; + let custom = ColorTable::colors(&table.custom_palette, "customPalette")?; + let to_clear = ColorTable::colors(&table.transparent, "transparent")?; + let opaque_left = |left: &[[u8; 3]]| left.iter().any(|c| !to_clear.contains(c)); + if custom.is_empty() { + let ix = quantize::quantize_locked(rgba, w, h, o, locked); + let clear = ix.transparent.map(usize::from); + let gone = |i: usize, c: &[u8; 3]| Some(i) != clear && deleted.contains(c); + if !ix.palette.iter().enumerate().any(|(i, c)| gone(i, c)) { + return Ok(ix); + } + let left: Vec<[u8; 3]> = ix.palette.iter().enumerate().filter(|&(i, c)| Some(i) != clear && !deleted.contains(c)).map(|(_, c)| *c).collect(); + if left.is_empty() || !opaque_left(&left) { + return Err(KEEP_ONE.into()); + } + return Ok(quantize::quantize_to(rgba, w, h, o, &left)); + } + // A fixed palette holds at most `colors` entries, the transparent one included. + let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128); + let removed = custom.iter().any(|c| deleted.contains(c)); + let mut left: Vec<[u8; 3]> = vec![]; + for c in custom { + if !deleted.contains(&c) && !left.contains(&c) { + left.push(c); + } + } + if left.is_empty() || (removed && !opaque_left(&left)) { + return Err(KEEP_ONE.into()); + } + // The colors mapped to transparent all become the one transparent entry, so together they take + // one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of + // them and no pixel is transparent, that slot goes to the next opaque color instead. + let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true); + let mut ix = quantize::quantize_to(rgba, w, h, o, &kept); + clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear); + if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) { + return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false))); + } + Ok(ix) +} + +/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in +/// `to_clear` are kept and take one slot together; without it they are left out. The list holds +/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry). +fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> { + let any_clear = clear && left.iter().any(|c| to_clear.contains(c)); + let total = 256 - usize::from(has_clear); + let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear)); + let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room); + let mut clear_room = if clear { total - opaque } else { 0 }; + left.iter() + .copied() + .filter(|c| { + let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room }; + let keep = *slots > 0; + *slots = slots.saturating_sub(1); + keep + }) + .collect() +} + +/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to +/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the +/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later. +fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) { + let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect(); + if dropped.is_empty() { + return; + } + let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); + let near = quantize::nearest_entries(rgba, o, &all); + if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) { + return; + } + let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) { + Some(i) => i, + None => { + // A kept color mapped to transparent that no pixel took; at most 255 entries are used then. + let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else { + return; + }; + ix.palette.push(*c); + i + } + }; + for (v, n) in ix.indices.iter_mut().zip(&near) { + if n.is_some_and(|n| n >= kept.len()) { + *v = entry; + } + } +} + /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). pub fn decode(o: &Optimized) -> std::result::Result<(Vec, u32, u32), String> { let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?; @@ -1051,7 +1225,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { .map(|c| { json!({ "color": hex(c.color), "source": hex(c.source), "transparent": c.transparent, "locked": c.locked, - "webShifted": c.web_shifted, "webSafe": quantize::web_safe(c.color) == c.color, + "webShifted": c.web_shifted, "shifted": c.shifted, "webSafe": quantize::web_safe(c.color) == c.color, }) }) .collect(); 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/doc_state.rs b/crates/engine/src/doc_state.rs index 9cbdfb6827..cabc774737 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -25,6 +25,10 @@ pub struct DocState { /// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`, /// `layer.highlight`). pub layer_rows: Vec, + /// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the + /// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also + /// when the row was already highlighted. Panel state: not saved, not undoable. + pub locate_reveal: Option, /// The variable highlighted in the Variables panel: what its Delete, Options… and Select /// Bound Object act on. Panel state, not art selection: not saved, not undoable /// (`variable.highlight`). A name, so renaming a variable moves the highlight with it. @@ -136,6 +140,10 @@ pub struct DocState { /// same document comes to the front, its type set in them is not measured again. While this /// reference lasts, its allocation holds no other document. Not saved. pub(crate) measured_in_own: Option<(std::sync::Weak, std::collections::HashSet)>, + /// The document as the last edit's refresh of inline graphics left it, and what that refresh + /// measured: the next refresh checks only the layer trees that differ from it + /// ([`cmd::inline::refresh`]). Not saved. + pub(crate) inline_resolved: Option, } /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that @@ -318,6 +326,7 @@ impl DocState { revision: 1, active_layer, layer_rows: vec![], + locate_reveal: None, variables_highlight: None, variables_sort: Default::default(), isolation: None, @@ -355,6 +364,7 @@ impl DocState { plugin_effects: Default::default(), art_to_fit: Default::default(), measured_in_own: None, + inline_resolved: None, } } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 3ab6a7dcb8..d472ec760c 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -32,6 +32,9 @@ pub struct HistoryEntry { pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// Owned new-art snapshots included in both directional estimates. color_mode_bytes: usize, + /// The state that changes without an undo step as the next state had it: undo and redo compare + /// it with `doc` to tell what the step changed. + pub(crate) unrecorded: Arc, } impl Clone for HistoryEntry { @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, + unrecorded: self.unrecorded.clone(), } } } @@ -94,6 +98,7 @@ impl HistoryEntry { serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, + unrecorded: Arc::new(crate::cmd::Unrecorded::of(next)), } } @@ -126,6 +131,7 @@ impl HistoryEntry { serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, + unrecorded: Arc::new(crate::cmd::Unrecorded::of(now)), } } @@ -337,6 +343,7 @@ impl History { e.next_bytes = after.saturating_add(e.color_mode_bytes); e.next = std::ptr::from_ref(now) as usize; e.serial = next_serial(); + e.unrecorded = Arc::new(crate::cmd::Unrecorded::of(now)); } } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7f4f49852d..94ea383690 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -28,7 +28,8 @@ use vectorcraft_tools::{PaintDefaults, Tool}; pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; -pub use cmd::distortcmds::perspective_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, 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 7a8c682baf..2a4cf188cd 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -10,6 +10,26 @@ pub enum DrawMode { Inside, } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run +/// may use ([`vectorcraft_plugins::Plugin::large_limits`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] +pub enum PluginBudget { + /// The plug-in's own limits. + #[default] + Normal, + /// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of + /// input; the time budget is unchanged. + Large, +} + +/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the +/// other preferences are read as they are. +fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + let saved = ::deserialize(d)?; + Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal }) +} + /// A saved Default Language as its tag: older preferences hold the language's name, and one the list /// no longer has reads as the default. fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { @@ -29,6 +49,12 @@ pub struct Prefs { pub constrain_angle: f64, pub corner_radius: f64, pub disable_auto_add_delete: bool, + /// General › Interpolate Control Points When Moving Anchors: the default of the `interpolate` + /// param of the commands that move direct-selected anchors (a Direct Selection drag, the arrow + /// keys, Move, Transform Again). On, the handles of each segment with one moved end are + /// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the + /// default), the handles of a moved anchor move with it and the other handles stay. + pub interpolate_control_points: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, /// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the @@ -74,6 +100,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 @@ -176,6 +209,11 @@ pub struct Prefs { pub fonts_folder: String, // Plug-ins & Scratch Disks pub plugins_folder: String, + /// Plug-in Instruction Budget: the instructions each object filter run gets, from + /// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers + /// keep their own budgets. + #[serde(deserialize_with = "plugin_budget")] + pub plugin_instruction_budget: PluginBudget, pub scratch_primary: String, pub scratch_secondary: String, // User Interface @@ -392,6 +430,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(); @@ -400,6 +453,7 @@ impl Default for Prefs { constrain_angle: 0.0, corner_radius: 12.0, disable_auto_add_delete: false, + interpolate_control_points: false, use_precise_cursors: false, show_tool_tips: true, show_tool_cards: false, @@ -423,6 +477,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, @@ -493,6 +549,7 @@ impl Default for Prefs { hyphenation_exceptions: String::new(), fonts_folder: String::new(), plugins_folder: String::new(), + plugin_instruction_budget: PluginBudget::Normal, scratch_primary: s("Startup"), scratch_secondary: s("None"), ui_brightness: s("mediumDark"), 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/session/edit.rs b/crates/engine/src/session/edit.rs index 8c0f3e8803..ce0c2998fe 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -53,7 +53,8 @@ impl Session { let mut symbol_synced = if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) }; // Inline graphics in text follow their symbols. - cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc)); + let measured = cmd::inline::refresh(st.inline_resolved.as_ref(), &before, Arc::make_mut(&mut st.doc)); + let mut resolved = measured.map(|m| (st.doc.clone(), m)); // The document the passes below start from, for the symbol to follow what they // change on its editing layer. let synced = st.doc.symbol_edit.is_some().then(|| st.doc.clone()); @@ -86,7 +87,10 @@ impl Session { let new = art(&st.doc); if symbol_synced.is_ok() && !matches!((&old, &new), (Some(a), Some(b)) if Arc::ptr_eq(a, b)) { let resynced = st.doc.clone(); - cmd::inline::refresh(synced, Arc::make_mut(&mut st.doc)); + let last = resolved.as_ref().or(st.inline_resolved.as_ref()); + if let Some(m) = cmd::inline::refresh(last, synced, Arc::make_mut(&mut st.doc)) { + resolved = Some((st.doc.clone(), m)); + } if !st.doc.text_threads.is_empty() { cmd::threads::reflow(&resynced, Arc::make_mut(&mut st.doc)); } @@ -100,6 +104,7 @@ impl Session { if !st.doc.variables.bindings.is_empty() { Arc::make_mut(&mut st.doc).prune_variable_bindings(); } + st.inline_resolved = resolved; if let Err(e) = symbol_synced { Err(e) } else if st.doc.too_deep(Some(&before)) { @@ -437,8 +442,10 @@ impl Session { // selected): Transform Again moves the selected anchors and the objects selected whole // by the same distance. A drag that ends where it began leaves the last transform. let mut options = serde_json::json!({ "copy": false }); - if let Some(patterns) = preview.1.get("patterns") { - options["patterns"] = patterns.clone(); + for key in ["patterns", "interpolate"] { + if let Some(v) = preview.1.get(key) { + options[key] = v.clone(); + } } st.last_transform = Some(LastTransform::Matrix(vectorcraft_geom::Affine::translate(moved), options)); st.last_perspective = None; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a16f01cfa0..38692e9056 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -85,6 +85,7 @@ mod history_mem; mod ids_without_selection; mod inline; mod interactivity; +mod interpolate_handles; mod intertwine; mod journal; mod keyanchor; @@ -122,6 +123,7 @@ mod paintproxy; mod panelcmds; mod paragraphs; mod params; +mod params_cache; mod path_menu_enabled; mod pathfinder_clip; mod pathops; @@ -371,9 +373,12 @@ fn a_long_unknown_command_id_is_answered_at_once() { fn action_batch_names_the_nearest_command_id() { let mut s = session(); let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "select.al"}]})).unwrap_err(); - assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `select.al`; did you mean `select.all`?"); + assert_eq!( + e.to_string(), + "invalid parameters for `action.batch`: action step 1 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?" + ); let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "nope"}]})).unwrap_err(); - assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `nope`"); + assert_eq!(e.to_string(), "invalid parameters for `action.batch`: action step 1 (`nope`) failed: unknown command `nope`"); } #[test] @@ -3215,6 +3220,101 @@ fn every_command_has_unique_id_and_doc() { assert!(command_specs().iter().all(|c| !c.params.is_empty() && !c.label.is_empty())); } +/// Ids that name no built-in command: commands only the app runs, near misses of real ids and +/// plug-in command ids of plug-ins that are not installed. +const NOT_BUILT_IN: &[&str] = + &["", "file.save", "file.open", "edit.preferences", "select", "select.none.", "SELECT.NONE", " select.none", "plugin.nobody.cmd", "plugin."]; + +/// The spec a search of the built-in list in order finds for `id`. +fn first_built_in(id: &str) -> Option<&'static CommandSpec> { + command_specs().iter().find(|c| c.id == id) +} + +#[test] +fn find_command_finds_the_spec_a_search_of_the_list_finds() { + let misses: Vec = NOT_BUILT_IN.iter().map(|id| (*id).to_string()).chain((0..200).map(|i| format!("missing.command{i}"))).collect(); + for id in command_specs().iter().map(|c| c.id.to_string()).chain(misses) { + let (found, first) = (find_command(&id), first_built_in(&id)); + assert!(found.map(std::ptr::from_ref) == first.map(std::ptr::from_ref), "{id:?}"); + assert_eq!(found.is_none(), NOT_BUILT_IN.contains(&id.as_str()) || id.starts_with("missing."), "{id:?}"); + } +} + +#[test] +fn the_command_index_keeps_the_first_spec_of_an_id() { + let base = &command_specs()[0]; + let specs = [ + CommandSpec { id: "test.twice", label: "First", ..*base }, + CommandSpec { id: "test.once", ..*base }, + CommandSpec { id: "test.twice", label: "Second", ..*base }, + ]; + let index = crate::cmd::index_by_id(&specs); + assert_eq!(index.len(), 2); + assert!(index.get("test.twice").is_some_and(|c| std::ptr::eq(*c, &specs[0]))); + assert!(index.get("test.once").is_some_and(|c| std::ptr::eq(*c, &specs[1]))); + assert!(!index.contains_key("test.none")); +} + +/// Times [`find_command`] against a search of the built-in list in order (the lookup before the +/// index), in one process, over every built-in id and 200 ids that name no command, and +/// `select.none` run 100,000 times on a document with one rectangle. +/// Run with `cargo test --release -p vectorcraft-engine --lib command_lookup_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn command_lookup_timing() { + use std::hint::black_box; + use std::time::Instant; + let hits: Vec<&str> = command_specs().iter().map(|c| c.id).collect(); + let missing: Vec = (0..200 - NOT_BUILT_IN.len()).map(|i| format!("missing.command{i}")).collect(); + let misses: Vec<&str> = NOT_BUILT_IN.iter().copied().chain(missing.iter().map(String::as_str)).collect(); + let linear = |id: &str| first_built_in(id).or_else(|| crate::cmd::plugin::find_spec(id)); + for id in hits.iter().chain(&misses) { + assert!(find_command(id).map(std::ptr::from_ref) == linear(id).map(std::ptr::from_ref), "{id:?}"); + } + let per_lookup = |ids: &[&str], f: &dyn Fn(&str) -> Option<&'static CommandSpec>| { + let rounds = 50; + let start = Instant::now(); + for _ in 0..rounds { + for id in ids { + black_box(f(black_box(id))); + } + } + start.elapsed().as_nanos() as f64 / (rounds * ids.len()) as f64 + }; + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("{} built-in ids, {} ids that name no command", hits.len(), misses.len()); + for (what, ids) in [("built-in id", &hits), ("no such command", &misses)] { + let (mut old, mut new) = (Vec::new(), Vec::new()); + for run in 0..7 { + // Alternates which lookup goes first, so a change in machine load falls on both. + if run % 2 == 0 { + old.push(per_lookup(ids, &linear)); + new.push(per_lookup(ids, &find_command)); + } else { + new.push(per_lookup(ids, &find_command)); + old.push(per_lookup(ids, &linear)); + } + } + println!("{what}: search of the list {old:.0?} ns, median {:.0}; index {new:.0?} ns, median {:.0}", median(old.clone()), median(new.clone())); + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let runs: Vec = (0..7) + .map(|_| { + let start = Instant::now(); + for _ in 0..100_000 { + black_box(s.execute("select.none", &json!({})).unwrap()); + } + start.elapsed().as_nanos() as f64 / 100_000.0 + }) + .collect(); + println!("select.none: {runs:.0?} ns a command, median {:.0}", median(runs.clone())); +} + #[test] fn every_command_survives_empty_params() { // Robustness: no command may panic on {} (with and without a selection). @@ -3293,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. @@ -3353,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() { @@ -4229,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/appearance.rs b/crates/engine/src/tests/appearance.rs index 53cbb42ca9..a04bb89b4a 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -227,6 +227,112 @@ fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() { assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0)); } +/// `brushed_strokes_profiled` reads the strokes `stroke.set` edits: a group's own stroke when it +/// has one, else its members'. It answers only while each of them draws with a brush, and not +/// while an object has no stroke row, which `stroke.set` would give a plain stroke. +#[test] +fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false), "both draw with a brush, neither has a profile"); + run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(true), "one has a profile"); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(true), "a group without its own stroke: its members'"); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert_eq!(s.brushed_strokes_profiled(), None, "the group's own plain stroke takes the profile"); + let c = rect(&mut s, 400.0); + run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1})); + assert!(node(&s, c).appearance.stroke().is_none()); + run(&mut s, "select.set", json!({"ids": [a.0, c.0]})); + assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke"); +} + +/// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count. +#[test] +fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 120.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let c = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": "add"}))["id"].as_u64().unwrap()); + assert!(node(&s, c).appearance.stroke().is_some_and(|st| st.brush.is_none()), "the compound shape's own plain stroke"); + s.edit("Brush", |d, _| { + for id in [a, b] { + if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + st.brush = Some("3 pt. Round".into()); + } + } + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [c.0]})); + assert_eq!(s.brushed_strokes_profiled(), None); + s.edit("Brush", |d, _| { + d.node_mut(c).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [c.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false)); +} + +/// A targeted layer with its own plain Stroke row active: `stroke.set` edits that row, so the +/// brushed path inside the layer does not count. +#[test] +fn brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row() { + let mut s = session(); + let a = rect(&mut s, 100.0); + run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"})); + let layer = s.doc().unwrap().doc.layers[0].id; + run(&mut s, "layer.target", json!({"id": layer.0})); + run(&mut s, "appearance.addStroke", json!({})); + let rows = &node(&s, layer).appearance.items; + let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_none())).expect("the layer's own stroke row"); + run(&mut s, "appearance.setActiveItem", json!({"index": index})); + assert_eq!(s.brushed_strokes_profiled(), None, "the layer's plain stroke takes the profile"); + run(&mut s, "stroke.set", json!({"profile": "lens"})); + assert!(node(&s, layer).appearance.items.get(index).is_some_and(|it| matches!(it, AppearanceItem::Stroke(st) if st.profile.is_some()))); + assert!(node(&s, a).appearance.stroke().is_some_and(|st| st.profile.is_none()), "the brushed path is left as it was"); +} + +/// A symbol instance selected with a brushed path takes no stroke from `stroke.set`, so it does +/// not count; the brushed path alone decides. +#[test] +fn brushed_strokes_profiled_leaves_out_symbol_instances() { + let mut s = session(); + let a = rect(&mut s, 100.0); + run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"})); + let r = rect(&mut s, 300.0); + run(&mut s, "select.set", json!({"ids": [r.0]})); + let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap()); + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. })); + run(&mut s, "select.set", json!({"ids": [a.0, inst.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false)); +} + +/// With the active row a stroke of the first object that another selected object has no equal +/// row for, `stroke.set` edits that object's top stroke, so its top stroke decides. +#[test] +fn brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"})); + run(&mut s, "stroke.set", json!({"ids": [b.0], "weight": 5})); + let rows = &node(&s, a).appearance.items; + let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_some())).expect("a's brushed stroke"); + assert!(index >= node(&s, b).appearance.items.len() || node(&s, b).appearance.items[index].is_fill(), "{rows:?}"); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut s, "appearance.setActiveItem", json!({"index": index})); + assert_eq!(s.brushed_strokes_profiled(), Some(false), "b's top stroke has the brush too"); +} + #[test] fn text_items_take_item_paint() { let mut s = session(); diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 1d571884a0..fff9ed9588 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -302,6 +302,23 @@ fn the_shared_settings_drive_the_export_and_arent_an_undo_step() { assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["formats"][0]["format"], "jpg"); } +/// The shared settings are not an undo step, so undo and redo of the steps before them leave them +/// as they are. +#[test] +fn undo_and_redo_keep_the_shared_settings() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + run(&mut s, "assets.add", json!({"ids": [a]})); + run(&mut s, "assets.settings.set", json!({"formats": [{"format": "svg"}], "prefix": "ic_"})); + let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings); + run(&mut s, "assets.settings.set", json!({"formats": [{"format": "jpg"}], "prefix": ""})); + let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone(); + run(&mut s, "edit.redo", json!({})); + assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings); +} + /// An export preset sets the shared settings as the Asset Export panel applies one: its rows (or /// mobile/density), its format settings over the saved ones, its prefix and its sub-folders. #[test] 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 4f0b739951..38aadcc712 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -110,13 +110,15 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "art-ribbons", "ink-and-wash", "calligraphic-nibs", + "pressure-sensitive", "bristle-brushes", "pattern-borders", "scatter-shapes", "game-trails", "energy-beams", "dry-media", - "tech-circuit" + "tech-circuit", + "arrows" ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); @@ -131,19 +133,25 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] ); - assert_eq!(libs[6]["count"].as_u64(), Some(4)); + assert_eq!(libs[7]["count"].as_u64(), Some(4)); let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"})); assert_eq!( beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"] ); - assert_eq!(libs[7]["count"].as_u64(), Some(4)); + assert_eq!(libs[8]["count"].as_u64(), Some(4)); let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"})); assert_eq!( dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] ); - assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4))); + 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]})); @@ -154,17 +162,19 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("art-ribbons", "art"), ("ink-and-wash", "art"), ("calligraphic-nibs", "calligraphic"), + ("pressure-sensitive", "art"), ("bristle-brushes", "bristle"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter"), ("game-trails", "art"), ("energy-beams", "art"), ("dry-media", "art"), + ("arrows", "art"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); for b in &lib.brushes { - let kind = if b.name == "Brush Pen" { "calligraphic" } else { kind }; + let kind = if ["Brush Pen", "Round Flow", "Chisel Flow"].contains(&b.name.as_str()) { "calligraphic" } else { kind }; assert_eq!(b.kind.type_id(), kind, "{}", b.name); let mut line = vectorcraft_geom::BezPath::new(); line.move_to((0.0, 0.0)); @@ -218,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() { @@ -299,6 +381,52 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Pressure Sensitive").unwrap(); + let names = ["Flex Ribbon", "Pulse Stroke", "Round Flow", "Chisel Flow"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap(); + let mut curve = line_to(20.0); + curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0)); + for b in &lib.brushes { + let width_at = |pressure| { + let stroke = vectorcraft_doc::StrokeLayer { + pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), + ..black_stroke() + }; + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at pressure {pressure}", b.name); + let min = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min); + let max = points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max); + max - min + }; + let light = width_at(0.0); + let heavy = width_at(1.0); + for width in [light, heavy] { + assert!(width.is_finite() && width > 0.0, "{}: light={light}, heavy={heavy}", b.name); + } + assert!(heavy > light * 1.3, "{}: light={light}, heavy={heavy}", b.name); + for line in [line_to(2.0), curve.clone()] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke()); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "pressure-sensitive", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + 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(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + /// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two /// translucent washes, with names of their own and a few paths of art each. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 7e3ce00834..3a3a07a2c1 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1289,6 +1289,29 @@ fn brush_freehand_continued_by_one_point_follows_keep_selected() { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step"); } +/// A `brush.freehand` call that continues a path by one point with a bad `connect` is refused +/// before the path's brush changes: the brush, the selection and the undo history stay as they were. +#[test] +fn brush_freehand_continued_by_one_point_refuses_a_bad_connect() { + let mut s = session(); + let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + select(&mut s, &[a]); + let undo = undo_steps(&s); + let one = json!({"points": [[120, 10]], "extend": {"id": p.0, "end": "end"}, "brush": "Dots"}); + for connect in + [json!({"id": p.0, "end": "end"}), json!({"id": a.0, "end": "middle"}), json!({"end": "end"}), json!({"id": 999_999, "end": "end"})] + { + let mut params = one.clone(); + params["connect"] = connect; + assert!(s.execute("brush.freehand", ¶ms).is_err(), "{params}"); + assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "{params}: the brush stays"); + assert_eq!(selected(&s), [a], "{params}: the selection stays"); + assert_eq!(undo_steps(&s), undo, "{params}: no undo step"); + } +} + /// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one /// and a new filled pencil path while the stroke is None) instead of reporting it painted: the /// document, the selection and the undo history stay as they were. Without a brush the path is @@ -1400,6 +1423,40 @@ fn paintbrush_tool_uses_the_current_brush() { assert!(s.execute("brush.setCurrent", &json!({"name": "Nope"})).is_err()); } +/// The current brush and symbol are not undo steps, so undo and redo of other steps leave them as +/// they are. With nothing else changed outside the history, undo back to the saved document leaves +/// it saved. +#[test] +fn undo_and_redo_keep_the_current_brush_and_symbol() { + let mut s = session(); + rect(&mut s, 10.0, 10.0, 20.0, 20.0); + s.execute("symbol.new", &json!({"name": "A"})).unwrap(); + rect(&mut s, 40.0, 10.0, 20.0, 20.0); + s.execute("symbol.new", &json!({"name": "B"})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + rect(&mut s, 70.0, 10.0, 20.0, 20.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.doc().unwrap().is_dirty(), "back at the saved document"); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap(); + s.execute("symbol.setCurrent", &json!({"name": "A"})).unwrap(); + let current = |s: &mut Session| { + let brush = s.execute("brush.list", &json!({})).unwrap()["current"].clone(); + (brush, s.execute("symbol.list", &json!({})).unwrap()["current"].clone()) + }; + let want = (json!("Arrow"), json!("A")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(current(&mut s), want); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(current(&mut s), want); + // A symbol made current between undoing and redoing its deletion is not kept as current. + s.execute("symbol.delete", &json!({"name": "B"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("currentSymbol"), Some(&json!("A"))); +} + /// A Size: Pressure variant of "3 pt. Round" (3 ± 3 pt). fn pressure_round(s: &mut Session) { let params = json!({"variation": [0, 0, 3], "modes": ["fixed", "fixed", "pressure"]}); @@ -1569,6 +1626,34 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() { assert_eq!(back.node(pen).unwrap().appearance.stroke(), doc.node(pen).unwrap().appearance.stroke()); } +/// A Bristle path made from pen samples keeps its input when saved and uses it when exported. +#[test] +fn bristle_path_keeps_and_draws_its_pen_pose() { + let mut s = session(); + let id = NodeId( + s.execute( + "brush.freehand", + &json!({"points": [[20, 60, 0.1, 10, 0, 0], [200, 60, 0.9, 35, 0, 90]], "style": "brush", "brush": "Bristle Round"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let doc: Document = (*s.doc().unwrap().doc).clone(); + let st = doc.node(id).unwrap().appearance.stroke().unwrap(); + assert!(st.pressure.is_some() && st.tilt.is_some() && st.bearing.is_some() && st.rotation.is_some()); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(back.node(id).unwrap().appearance.stroke(), Some(st)); + + let mut neutral = doc.clone(); + let st = neutral.node_mut(id).unwrap().appearance.stroke_mut().unwrap(); + st.pressure = None; + st.tilt = None; + st.bearing = None; + st.rotation = None; + assert_ne!(vectorcraft_svg::export(&doc, &Default::default()), vectorcraft_svg::export(&neutral, &Default::default())); +} + /// Pen pressure belongs to its path: new art, graphic styles and Brush Options' edits leave it. #[test] fn pressure_stays_with_its_own_path() { @@ -1612,6 +1697,46 @@ fn brush_options_set_variation_modes() { assert_eq!(s.execute("brush.get", &json!({"name": "Dots"})).unwrap()["modes"], modes); } +/// The fill colors of the copies brushed path `id` draws in `doc`, as `#rrggbb`. +fn piece_fills(doc: &Document, id: NodeId) -> Vec { + let pieces = vectorcraft_brush::node_pieces(doc, doc.node(id).unwrap()).expect("brushed"); + pieces.iter().map(|n| n.appearance.fill_paint().color().unwrap().to_hex()).collect() +} + +/// Scatter Brush Options' `hue_jitter`: shown by `brush.get`, set by `brush.options`, saved with the +/// document, and the turned colors drawn the same after Open and written by SVG export. +#[test] +fn scatter_hue_jitter_saves_and_exports() { + let mut s = session(); + let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string(); + let id = line(&mut s); + select(&mut s, &[id]); + s.execute("brush.apply", &json!({ "name": name })).unwrap(); + let plain = piece_fills(&s.doc().unwrap().doc, id); + assert!(plain.len() > 10 && plain.iter().all(|c| c == "#ff0000"), "{plain:?}"); + assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(0.0), "brush.get shows the option at 0"); + s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 120}})).unwrap(); + assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(120.0)); + let doc = s.doc().unwrap().doc.clone(); + let turned = piece_fills(&doc, id); + assert_eq!(turned.len(), plain.len()); + let distinct: std::collections::HashSet<&String> = turned.iter().collect(); + assert!(distinct.len() > 5, "{turned:?}"); + // Saved and opened again, the stroke draws the same colors. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(piece_fills(&back, id), turned); + // SVG export writes each copy's turned color. + let svg = vectorcraft_svg::export(&doc, &Default::default()); + for c in &distinct { + assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG"); + } + // Back to 0, the copies draw the art's own color. + s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 0}})).unwrap(); + assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain); +} + /// The bounds of the brush art `id`'s strokes draw. fn brushed_bounds(s: &Session, id: NodeId) -> Rect { let st = s.doc().unwrap(); @@ -2074,6 +2199,212 @@ fn break_link_then_update_redefines_all_instances() { assert!((bounds(&s, other).center().x - 300.0).abs() < 1e-6); } +/// Redefine Symbol with `keepArt: true` updates the symbol and its instances from the selection, +/// and the selected art stays ordinary art in its place, with its ids, still selected; the result +/// has no instance id. One undo step takes the definition back. Without `keepArt`, or with false, +/// the art becomes an instance. +#[test] +fn redefine_with_keep_art_leaves_the_art_as_ordinary_art() { + let mut s = session(); + let (inst, name, _) = make_symbol(&mut s); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i)); + let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)); + let symbol_art = |s: &Session| s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap(); + let old_art = symbol_art(&s); + let steps = s.doc().unwrap().history.undo.len(); + select(&mut s, &[a, b]); + let r = s.execute("symbol.update", &json!({"name": name, "keepArt": true})).unwrap(); + assert_eq!(r, json!({"name": name, "id": null})); + assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected"); + let instances = |s: &Session| { + let mut n = 0; + s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. }))); + n + }; + assert_eq!(instances(&s), 1, "no new instance"); + // The instance shows the new art: the 120 × 50 pair. + let w = bounds(&s, inst); + assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(symbol_art(&s), old_art, "undo takes the definition back"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!((bounds(&s, inst).width() - 120.0).abs() < 1e-6, "{:?}", bounds(&s, inst)); + // false, like no keepArt, makes the art an instance. + for p in [json!({"name": name, "ids": [a.0], "keepArt": false}), json!({"name": name, "ids": [b.0]})] { + let r = s.execute("symbol.update", &p).unwrap(); + let id = NodeId(r["id"].as_u64().expect("an instance id")); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}"); + } + assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none()); +} + +/// Redefine Symbol with `keepArt: true` and explicit ids keeps the named art selected only where +/// it can be selected: locked or hidden art is left out. A `keepArt` that is not true or false is +/// refused, with no change and no undo step. +#[test] +fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() { + let mut s = session(); + let (_, name, _) = make_symbol(&mut s); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0); + { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(locked).unwrap().locked = true; + doc.node_mut(hidden).unwrap().visible = false; + } + for bad in [json!("true"), json!(1), json!([true])] { + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let e = s.execute("symbol.update", &json!({"name": name, "ids": [a.0], "keepArt": bad})).unwrap_err(); + assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step"); + } + select(&mut s, &[]); + s.execute("symbol.update", &json!({"name": name, "ids": [a.0, locked.0, hidden.0], "keepArt": true})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![a], "only the selectable art is selected"); + for id in [a, locked, hidden] { + assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art"); + } +} + +/// The number of symbol instances in the document. +fn instance_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. }))); + n +} + +/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current +/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the +/// result has no instance id and nothing places the symbol. One undo step takes the symbol away +/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance. +#[test] +fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() { + let mut s = session(); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i)); + let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)); + let steps = s.doc().unwrap().history.undo.len(); + select(&mut s, &[a, b]); + let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap(); + assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}"); + assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected"); + assert_eq!(instance_count(&s), 0, "no instance"); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0))); + // The symbol's art is the pair: an instance placed from it is 120 × 50. + let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap()); + let w = bounds(&s, placed); + assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away"); + assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo"); + assert_eq!(instance_count(&s), 0, "redo places no instance"); + // false, like no keepArt, makes the art an instance. + for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] { + let r = s.execute("symbol.new", &p).unwrap(); + let id = NodeId(r["id"].as_u64().expect("an instance id")); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}"); + } + assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none()); +} + +/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it +/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the +/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and +/// no undo step. +#[test] +fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() { + let mut s = session(); + let (inst, _, _) = make_symbol(&mut s); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0); + { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(locked).unwrap().locked = true; + doc.node_mut(hidden).unwrap().visible = false; + } + for bad in [json!("true"), json!(1), json!([true])] { + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err(); + assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step"); + } + select(&mut s, &[]); + let symbols = s.doc().unwrap().doc.symbols.len(); + let ids = [a.0, locked.0, hidden.0, inst.0]; + s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1); + let selected = &s.doc().unwrap().selection.objects; + assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}"); + for id in [a, locked, hidden] { + assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art"); + } + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance"); + assert_eq!(instance_count(&s), 1, "no new instance"); +} + +/// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a +/// group, in an opacity mask, or through the art of another symbol it holds an instance of, and +/// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines +/// it. +#[test] +fn redefine_refuses_art_holding_an_instance_of_the_symbol() { + let mut s = session(); + let (inst, name, _) = make_symbol(&mut s); + // Ring's art is an instance of Box. + let ring = NodeId(s.execute("symbol.new", &json!({"name": "Ring", "ids": [inst.0]})).unwrap()["id"].as_u64().unwrap()); + let place = + |s: &mut Session, x: f64| NodeId(s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap()["id"].as_u64().unwrap()); + let direct = place(&mut s, 300.0); + let plain = rect(&mut s, 20.0, 220.0, 30.0, 30.0); + let grouped = place(&mut s, 100.0); + // A rectangle whose opacity mask is a Box instance. + let masked = rect(&mut s, 60.0, 260.0, 30.0, 30.0); + let mut mask_art = node(&s, direct); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + mask_art.id = doc.alloc_id(); + doc.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask_art, true))); + let cases = [ + ("a Box instance", vec![direct.0]), + ("Ring, whose art holds Box", vec![ring.0]), + ("art with a Box instance", vec![plain.0, grouped.0]), + ("art masked by a Box instance", vec![masked.0]), + ]; + for (case, ids) in cases { + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("symbol.update", &json!({"name": name, "ids": ids})).unwrap_err(); + assert!(e.to_string().contains("can't hold an instance of itself"), "{case}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{case}: the document is unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{case}: no undo step"); + } + // An instance of a symbol that does not hold Box redefines it. + let dot = rect(&mut s, 200.0, 20.0, 10.0, 10.0); + let dot = NodeId(s.execute("symbol.new", &json!({"name": "Dot", "ids": [dot.0]})).unwrap()["id"].as_u64().unwrap()); + let r = s.execute("symbol.update", &json!({"name": name, "ids": [dot.0]})).unwrap(); + assert_eq!(r["name"], json!(name)); + let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap(); + assert!(matches!(&art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Dot"), "{}", art.kind_label()); +} + /// A linked opacity mask of a 10 × 10 square at (100, 50). fn square_mask(s: &mut Session) -> Box { let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 52c6ffa271..33483c5e21 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1083,6 +1083,36 @@ fn shape_builder_drops_a_press_held_during_a_merge() { } } +/// When `tool.setOption` names no tool, the option is set on the tool that was active when the +/// call arrived (the Shape Builder), even when finishing its merge replays a held Cmd press that +/// switches to the Selection tool. +#[test] +fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() { + let v = ViewInfo::default(); + let mut s = session(); + s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap(); + square_row(&mut s); + click_row(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Down, 305.0, 10.0).with_mods(Mods { cmd: true, ..Default::default() }), v).unwrap(); + assert!(s.tool_editing(), "the press is held"); + let out = s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "artwork"})).unwrap(); + assert_eq!(s.tool_id(), "selection", "the held press lent the selection tool"); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder")); + assert_eq!(out["pickColorFrom"], json!("artwork")); + assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork"))); + // Named while it waits, the Shape Builder is read where it waits, not made afresh from the + // preferences. + s.lender.as_mut().unwrap().set_option("pickColorFrom", &json!("swatches")); + let read = s.set_tool_option_cmd(&json!({"tool": "shapeBuilder"})).unwrap(); + assert_eq!(read["pickColorFrom"], json!("swatches"), "read from the waiting tool"); + // A value set on it counts as set on the tool chosen. + s.tool_set_since_reset = false; + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "key": "highlightFill", "value": false})).unwrap(); + assert!(s.tool_set_since_reset(), "the tool chosen was set"); + assert_eq!(s.lender.as_ref().map(|t| t.options()["highlightFill"].clone()), Some(json!(false))); +} + /// A new revision of the document made outside a command while a merge is computed on another /// thread keeps the merge when the selected art is as it was (the next poll applies it, as the /// command computes it), and drops it when the art changed. @@ -4997,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. @@ -5068,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/circle_through.rs b/crates/engine/src/tests/circle_through.rs index 25fcc04beb..e91c48e76a 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -1,5 +1,6 @@ -//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor -//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it. +//! `shape.circleThroughPoints`: a circle through two or three given points, or through the two or +//! three anchor points selected with Direct Selection, the Ellipse tool's three Shift-clicks that +//! run it, and the Circle tool. use serde_json::{Value, json}; use vectorcraft_doc::{LiveShape, Node, NodeKind}; @@ -95,13 +96,42 @@ fn coincident_or_collinear_points_are_refused() { assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}"); } -/// Points that are not three pairs of finite numbers are an error, not a fallback. +/// Two points are the ends of a diameter: (20, 40) and (100, 100) give the circle centered at +/// (60, 70) with radius 50, through both points, in one undo step. Two points that are the same +/// are refused, and so is a circle that would reach past the canvas, from two points or from three +/// nearly on one line; nothing is drawn and no undo step is recorded. +#[test] +fn two_points_are_the_ends_of_a_diameter() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"points": [[20, 40], [100, 100]]})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(60.0), Some(70.0), Some(50.0)), "{out}"); + let id = id_of(&out); + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(10.0, 20.0, 110.0, 120.0))); + assert!(farthest_from_path(&s, id, &[Point::new(20.0, 40.0), Point::new(100.0, 100.0)]) < 50.0 * 3e-4); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + let (undo, count) = (undo_len(&s), object_count(&s)); + let e = s.execute(C, &json!({"points": [[30, 30], [30, 30]]})).unwrap_err().to_string(); + assert!(e.contains("no circle passes through these points"), "{e}"); + // 4,100,000 pt across, past the canvas's 4,000,000 pt from the origin; and three points 0.001 pt + // off a chord 200 pt long, whose circle has a radius of about 5,000,000 pt. + for points in [json!([[0, 0], [4_100_000, 0]]), json!([[0, 0], [200, 0], [100, 0.001]])] { + let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{points}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// Points that are not two or three pairs of finite numbers are an error, not a fallback. #[test] fn malformed_points_are_refused() { let mut s = session(); let undo = undo_len(&s); for points in [ - json!([[0, 0], [10, 0]]), + json!([[0, 0]]), + json!([]), + json!([[0, 0], [10]]), json!([[0, 0], [10, 0], [0, 10], [5, 5]]), json!([[0, 0], [10, 0], [0]]), json!([[0, 0], [10, 0], ["0", 10]]), @@ -109,12 +139,12 @@ fn malformed_points_are_refused() { json!([[0, 0], [10, 0], [0, 10, 3]]), ] { let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string(); - assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}"); + assert!(e.contains("`points` must be two or three [x, y] pairs of numbers"), "{points}: {e}"); } assert_eq!(undo_len(&s), undo); } -/// With `points` left out, the three anchor points selected with Direct Selection give the +/// With `points` left out, the two or three anchor points selected with Direct Selection give the /// circle, from one path or several; any other number of them is an error. #[test] fn three_direct_selected_anchor_points_give_the_circle() { @@ -130,11 +160,15 @@ fn three_direct_selected_anchor_points_give_the_circle() { s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); let out = s.execute(C, &json!({"points": null})).unwrap(); assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}"); - // Two or four anchors, or a path of four anchors selected whole. - for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] { + // Two anchors are the ends of a diameter: (0, 0) and (80, 0). + s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}"); + // One or four anchors, or a path of four anchors selected whole. + for picked in [json!([[0, 0]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] { s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap(); let e = s.execute(C, &json!({})).unwrap_err().to_string(); - assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}"); + assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{picked}: {e}"); } s.execute("select.set", &json!({"ids": [path.0]})).unwrap(); assert!(s.execute(C, &json!({})).is_err()); @@ -153,7 +187,7 @@ fn three_direct_selected_anchor_points_give_the_circle() { s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3)); let e = s.execute(C, &json!({})).unwrap_err().to_string(); - assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}"); + assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{e}"); assert_eq!(undo_len(&s), undo); } diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 2d024f552b..660b24d6f6 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -594,6 +594,78 @@ fn separations_preview_compares_the_visible_plates_as_a_set() { assert!(r["plates"].as_array().unwrap().iter().all(|p| p["visible"] == false), "{r}"); } +/// Each plate's visibility in a `view.separationsPreview` or `color.plates` reply, in plate order. +fn visible_plates(r: &Value) -> Vec { + r["plates"].as_array().unwrap().iter().map(|p| p["visible"].as_bool().unwrap()).collect() +} + +/// A session whose document has the process plates and the spot plate `Brand Orange`. +fn session_with_spot_plate() -> Session { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Brand Orange", "color": {"c": 0, "m": 60, "y": 100, "k": 0}, "global": true})).unwrap(); + s.execute("swatch.setSpot", &json!({"name": "Brand Orange"})).unwrap(); + let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Brand Orange"})).unwrap(); + s +} + +/// `soloToggle` (the panel's Alt-click on a plate's eye) shows that plate alone, and every plate +/// when it already shows alone. A hidden plate, a plate among others, another solo plate and an +/// empty set of plates all give the named plate alone. It leaves the document's undo list and +/// modified state alone. +#[test] +fn separations_preview_solo_toggle_shows_every_plate_the_second_time() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session_with_spot_plate(); + let undo = s.doc().unwrap().history.undo.len(); + let dirty = s.doc().unwrap().is_dirty(); + let solo = |s: &mut Session, n: &str| visible_plates(&s.execute("view.separationsPreview", &json!({"soloToggle": n})).unwrap()); + // Off: the preview turns on with the plate alone. + assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]); + assert_eq!(vectorcraft_render::proof::view().separations, Some(vec!["Cyan".to_string()])); + // The same plate again: every plate, the spot plate included, and the preview stays on. + assert_eq!(solo(&mut s, "Cyan"), [true; 5]); + assert!(vectorcraft_render::proof::view().separations.is_some(), "the preview stays on"); + // A plate shown among others, then another plate while one shows alone. + assert_eq!(solo(&mut s, "Magenta"), [false, true, false, false, false]); + assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]); + // A hidden plate. + s.execute("view.separationsPreview", &json!({"toggle": "Black"})).unwrap(); + assert_eq!(solo(&mut s, "Yellow"), [false, false, true, false, false]); + // No plate shown. + s.execute("view.separationsPreview", &json!({"plates": []})).unwrap(); + assert_eq!(solo(&mut s, "Black"), [false, false, false, true, false]); + // The spot plate alone, then every plate. + assert_eq!(solo(&mut s, "Brand Orange"), [false, false, false, false, true]); + assert_eq!(solo(&mut s, "Brand Orange"), [true; 5]); + // A plate the document doesn't have is an error and leaves the view as it is. + let before = vectorcraft_render::proof::view(); + assert!(s.execute("view.separationsPreview", &json!({"soloToggle": "Mauve"})).is_err()); + assert_eq!(vectorcraft_render::proof::view(), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(s.doc().unwrap().is_dirty(), dirty, "not marked modified"); + // `only` stays a setter: the same plate again keeps it alone. + s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap(); + let r = s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap(); + assert_eq!(visible_plates(&r), [true, false, false, false, false]); +} + +/// A plate counts as shown alone when no other plate of the active document shows: names left in +/// the visible set by another document's plates don't count. +#[test] +fn separations_preview_solo_toggle_counts_the_active_documents_plates() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session_with_spot_plate(); + s.execute("view.separationsPreview", &json!({"plates": ["Cyan", "Brand Orange"]})).unwrap(); + // A new document without the spot plate: Cyan is the only one of its plates shown. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert_eq!(visible_plates(&s.execute("color.plates", &json!({})).unwrap()), [true, false, false, false]); + let r = s.execute("view.separationsPreview", &json!({"soloToggle": "Cyan"})).unwrap(); + assert_eq!(visible_plates(&r), [true; 4]); +} + #[test] fn proof_setup_simulates_tritanopia() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); 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/draw2.rs b/crates/engine/src/tests/draw2.rs index 8fa31889a2..dfa3e95aba 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -414,6 +414,61 @@ fn pencil_refuses_an_unknown_style_or_extend_end() { assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}"); } +/// `path.freehand` refuses a `connect` without `extend`, and checks a `connect` given with `extend` +/// before a stroke of one point returns, so a bad one is refused there too; a refused call changes +/// neither the document nor the undo history. A `connect` of null is a key left out. +#[test] +fn pencil_refuses_connect_without_extend_and_a_bad_connect_for_one_point() { + let mut s = session(); + let a = line(&mut s, 100.0, 100.0, 200.0, 100.0); + let b = line(&mut s, 300.0, 200.0, 400.0, 200.0); + let closed = NodeId(s.execute("path.create", &json!({"d": "M0 500 L50 500 L50 550 Z"})).unwrap()["id"].as_u64().unwrap()); + let inner = NodeId(s.execute("path.create", &json!({"d": "M600 500 L650 500"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [inner.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let stroke = json!({"points": [[200, 100], [250, 150], [300, 200]]}); + for connect in [json!({"id": b.0, "end": "start"}), json!({"id": b.0, "end": "middle"}), json!({"id": b.0}), json!({})] { + refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "connect": connect })), "connect needs extend"); + refuses_with(&mut s, "path.freehand", &with(&stroke, json!({"extend": null, "connect": connect})), "connect needs extend"); + } + let refused = |s: &mut Session, p: &serde_json::Value| { + let before = s.doc().unwrap().doc.clone(); + let undo = undo_steps(s); + assert!(s.execute("path.freehand", p).is_err(), "{p}"); + assert!(s.doc().unwrap().doc == before, "{p} changed the document"); + assert_eq!(undo_steps(s), undo, "{p} left an undo step"); + }; + refused(&mut s, &with(&stroke, json!({"connect": "b"}))); + let one = json!({"points": [[200, 100]], "extend": {"id": a.0, "end": "end"}}); + let end = "connect end must be \"start\" or \"end\""; + for e in [json!("middle"), json!(1), json!(null)] { + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0, "end": e}})), end); + } + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0}})), end); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"end": "end"}})), "connect needs id"); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": "b", "end": "end"}})), "`id` must be a whole number"); + let other = "connect needs a path other than the one extended"; + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": a.0, "end": "end"}})), other); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": closed.0, "end": "end"}})), "connect path has no open end"); + for p in [ + with(&one, json!({"connect": "b"})), + with(&one, json!({"connect": {"id": 999_999, "end": "end"}})), + with(&one, json!({"connect": {"id": group.0, "end": "end"}})), + ] { + refused(&mut s, &p); + } + assert_eq!((paths(&s).len(), path(&s, a).anchor_count(), path(&s, b).anchor_count()), (4, 2, 2), "refused: nothing changed"); + // A good `connect`, or a null one, on a stroke of one point leaves the path as it was. + let undo = undo_steps(&s); + for connect in [json!({"id": b.0, "end": "start"}), json!(null)] { + assert_eq!(s.execute("path.freehand", &with(&one, json!({ "connect": connect }))).unwrap()["id"], json!(a.0)); + } + assert_eq!((path(&s, a).anchor_count(), undo_steps(&s)), (2, undo)); + // Null without `extend`, `connect` is left out, and the stroke draws a new path. + s.execute("path.freehand", &with(&stroke, json!({"connect": null}))).unwrap(); + assert_eq!(paths(&s).len(), 5); +} + /// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath /// that connect joins on is no longer selected, and Delete then has nothing to delete. #[test] @@ -6292,14 +6347,20 @@ fn pencil_at_the_lowest_fidelity_takes_degenerate_strokes() { } } -/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's stays at 0.05 or more. +/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's 0.05 or more: a lower Fidelity is +/// an error that leaves the option as it was. #[test] fn pencil_option_takes_a_hundredth_and_smooth_keeps_its_floor() { let mut s = session(); - for (tool, want) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] { - s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap(); - assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(want), "{tool}"); - s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})).unwrap(); + for (tool, floor) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] { + let before = s.tool_options_of(tool)["fidelity"].clone(); + let e = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap_err(); + assert_eq!(e, format!("tool `{tool}`: `fidelity` must be a number from {floor} to 100")); + assert_eq!(s.tool_options_of(tool)["fidelity"], before, "{tool}"); + s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": floor}})).unwrap(); + assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(floor), "{tool}"); + let hundredth = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})); + assert_eq!(hundredth.is_ok(), tool != "smooth", "{tool}"); assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(if tool == "smooth" { 0.05 } else { 0.02 }), "{tool}"); } } diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 0cc0106351..b9a90f55c7 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -260,6 +260,100 @@ fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() { assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}"); let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}"); + assert_eq!(hit_at(&s, 30.5, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the added stroke"); +} + +/// What a click at (`x`, 100) with `opt` hits. +fn hit_at(s: &Session, x: f64, opt: vectorcraft_doc::hit::HitOptions) -> Option { + vectorcraft_doc::hit::hit_test(&s.doc().unwrap().doc, vectorcraft_geom::Point::new(x, 100.0), opt).map(|h| h.leaf) +} + +/// [`instance_with_row`] of a symbol whose art is an instance of another symbol made of the square. +fn nested_instance_with_row(s: &mut Session) -> (NodeId, usize) { + square(s); + let inner = NodeId(run(s, "symbol.new", json!({"name": "Inner"}))["id"].as_u64().unwrap()); + run(s, "select.set", json!({"ids": [inner.0]})); + let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap()); + run(s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(s, id).appearance.items.len() - 1; + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + (id, row) +} + +/// Effect › Pathfinder › Add on a group holding a symbol instance combines the art the instance +/// draws: the effects on the instance's fill and stroke reshape the result as they reshape the +/// instance, in a symbol placed inside another symbol too. +#[test] +fn pathfinder_takes_a_symbol_instance_fill_and_stroke_effects() { + for (fill, x, color) in [(true, 44, RED), (false, 40, BLUE)] { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", fill); + offset_row(&mut s, id, row, 10.0); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + let r = render(&s); + assert!(near(r.pixel(x, 100), color), "fill {fill}: the result keeps the offset: {:?}", r.pixel(x, 100)); + assert!(near(r.pixel(100, 100), RED), "fill {fill}: the result keeps the art's fill: {:?}", r.pixel(100, 100)); + } + // An effect of the instance's own reshapes the art as well. + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 10.0); + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}})); + assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100)); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the result: {:?}", render(&s).pixel(37, 100)); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows on the canvas: {:?}", render(&s).pixel(44, 100)); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows in the result: {:?}", render(&s).pixel(44, 100)); +} + +/// A click where the effect on a symbol instance's fill or stroke paints its art outside the +/// instance's bounds selects the instance; a click past the drawn art, a fill with Selection by +/// Path Only and outline mode do not. +#[test] +fn a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert_eq!(hit_at(&s, 44.0, opt), None); + offset_row(&mut s, id, row, 10.0); + assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill"); + assert_eq!(hit_at(&s, 100.0, opt), Some(id), "a click inside the instance"); + assert_eq!(hit_at(&s, 36.0, opt), None, "a click past the grown fill"); + assert_eq!(hit_at(&s, 44.0, HitOptions { path_only: true, ..opt }), None, "Selection by Path Only leaves the fill out"); + assert_eq!(hit_at(&s, 44.0, HitOptions { outline: true, ..opt }), None, "outline mode draws the art as it is"); + + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", false); + offset_row(&mut s, id, row, 10.0); + assert_eq!(hit_at(&s, 40.0, opt), Some(id), "a click on the moved stroke"); + assert_eq!(hit_at(&s, 45.0, opt), None, "a click between the moved stroke and the fill"); + assert_eq!(hit_at(&s, 40.0, HitOptions { path_only: true, ..opt }), Some(id), "Selection by Path Only takes the stroke"); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill of the nested art"); + + // A path in the art with an Offset Path of its own: both offsets grow what it draws. + let mut s = session(); + let art = square(&mut s); + run(&mut s, "effect.apply", json!({"ids": [art.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Offset"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 10.0); + assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100)); + assert_eq!(hit_at(&s, 37.0, opt), Some(id), "a click where both offsets grow the art"); } /// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what @@ -284,6 +378,7 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}"); let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}"); + assert_eq!(hit_at(&s, 35.0, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the group's grown fill"); let before = render(&s); run(&mut s, "effect.expandAppearance", json!({})); @@ -292,6 +387,181 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); } +/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115; +/// the fill's shape is 9 pt larger on each side. +fn image_with_shaped_fill(s: &mut Session) -> NodeId { + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + run(s, "select.set", json!({"ids": [im.0]})); + run(s, "appearance.addFill", json!({})); + run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0})); + run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0})); + im +} + +/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in +/// outline with `outline`. +fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec { + let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0); + vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline, false) +} + +/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its +/// art outside its box, as a click there selects it, except in outline. +#[test] +fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), []); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill"); + assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill"); + assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is"); + + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", false); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke"); + assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill"); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art"); +} + +/// A marquee touches an image where the shape of its own fill lies outside its frame, and an +/// instance of a symbol made of that image where the instance's fill effect grows that shape, as +/// clicks there select them, except in outline. +#[test] +fn a_marquee_on_the_shape_of_an_image_fill_selects_it() { + let mut s = session(); + let im = image_with_shaped_fill(&mut s); + assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame"); + assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape"); + assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame"); + + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill"); + assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill"); +} + +/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill +/// effect grows what that fill paints, and a click there selects the instance. +#[test] +fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() { + let mut s = session(); + image_with_shaped_fill(&mut s); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 70.0, opt), None); + offset_row(&mut s, id, row, 10.0); + assert!(near(render(&s).pixel(70, 100), BLUE), "the image's fill grows by the offset: {:?}", render(&s).pixel(70, 100)); + assert_eq!(hit_at(&s, 70.0, opt), Some(id), "a click on the image's grown fill"); + assert_eq!(hit_at(&s, 60.0, opt), None, "a click past the grown fill"); +} + +/// A group in the symbol's art with Effect › Pathfinder › Subtract: the instance's fill effect +/// grows the result, and a click past both shapes where only the subtracted shape would grow does +/// not select the instance. +#[test] +fn a_click_on_a_shape_a_pathfinder_effect_in_the_art_subtracts_misses_the_instance() { + let mut s = session(); + // The back square runs from 50 to 110 and the front one from 80 to 140; the result runs from 50 to 80. + let back = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"weight": 4})); + let front = NodeId(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap()); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [back.0, front.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.subtract"})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Subtracted"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 45.0, opt), None); + offset_row(&mut s, id, row, 10.0); + let r = render(&s); + assert!(near(r.pixel(45, 100), RED), "the result's fill grows by the offset: {:?}", r.pixel(45, 100)); + assert!(near(r.pixel(145, 100), WHITE), "the subtracted shape is not drawn: {:?}", r.pixel(145, 100)); + assert_eq!(hit_at(&s, 45.0, opt), Some(id), "a click on the result's grown fill"); + assert_eq!(hit_at(&s, 145.0, opt), None, "a click where only the subtracted shape would grow"); +} + +/// A Shaper group in the symbol's art: the instance's fill effect grows the faces it shows, and a +/// click where only its original shapes would grow does not select the instance. +#[test] +fn a_click_on_a_shaper_groups_original_shapes_in_the_art_misses_the_instance() { + let mut s = session(); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": []})); + for x in [0, 50] { + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []})); + run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100})); + } + // The scribble inside the overlap removes the front rectangle's face; the face left runs from 0 to 50. + let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap()); + assert!(node(&s, g).extras().shaper.is_some()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 57.0, opt), None); + offset_row(&mut s, id, row, 10.0); + let r = render(&s); + assert!(near(r.pixel(57, 100), RED), "the face's fill grows by the offset: {:?}", r.pixel(57, 100)); + assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100)); + assert_eq!(hit_at(&s, 57.0, opt), Some(id), "a click on the face's grown fill"); + assert_eq!(hit_at(&s, 125.0, opt), None, "a click on an original shape"); +} + +/// A Shaper group in the symbol's art with a stroke of its own below its Contents row: the +/// instance's stroke effect moves what that stroke paints, and a click selects the instance where +/// the canvas draws the moved stroke, not inside the original shapes. +#[test] +fn a_click_on_a_shaper_group_with_a_stroke_below_its_contents_selects_the_instance_where_it_draws() { + let mut s = session(); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": []})); + for x in [0, 50] { + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []})); + run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100})); + } + // The scribble removes the front rectangle's face; the group's stroke outlines both rectangles. + let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + let stroke = node(&s, g).appearance.items.len() - 1; + run(&mut s, "paint.setStroke", json!({"ids": [g.0], "item": stroke, "color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"ids": [g.0], "item": stroke, "weight": 4})); + run(&mut s, "appearance.moveItem", json!({"ids": [g.0], "from": "contents", "to": stroke + 1})); + assert_eq!(node(&s, g).appearance.split_contents().0.len(), stroke + 1, "the group's stroke is below its Contents row"); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 10.0); + let r = render(&s); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert!(near(r.pixel(160, 100), BLUE), "the group's stroke moves out by the offset: {:?}", r.pixel(160, 100)); + assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100)); + assert_eq!(hit_at(&s, 160.0, opt), Some(id), "a click on the group's moved stroke"); + assert_eq!(hit_at(&s, 125.0, opt), None, "a click inside an original shape"); +} + /// Of several fills, only the topmost one's effects reach the art, and only while it is visible. #[test] fn only_the_topmost_visible_instance_fill_reshapes_the_art() { 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/inline.rs b/crates/engine/src/tests/inline.rs index b6ea42d3f2..1d68881b4d 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -529,6 +529,245 @@ fn saved_documents_keep_inline_graphics() { assert_eq!(t.cached_bounds, obj(&s, id).cached_bounds); } +/// `groups` groups of `each` 5 × 5 black rectangles added to the first layer in one edit; returns +/// the ids of each group's rectangles. +fn rect_groups(s: &mut Session, groups: usize, each: usize) -> Vec> { + s.edit("Rectangles", |d, _| { + let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + let mut ids = vec![]; + let mut made = vec![]; + for g in 0..groups { + let kids: Vec> = (0..each) + .map(|i| { + let r = Rect::new(i as f64 * 6.0, g as f64 * 6.0, i as f64 * 6.0 + 5.0, g as f64 * 6.0 + 5.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look.clone())) + }) + .collect(); + ids.push(kids.iter().map(|k| k.id).collect()); + made.push(Arc::new(Node::group(d.alloc_id(), kids))); + } + match Arc::make_mut(&mut d.layers[0]).children_mut() { + Some(kids) => kids.extend(made), + None => panic!("the first layer holds art"), + } + Ok(ids) + }) + .unwrap() +} + +/// Runs `step` on `full`, with every refresh of inline graphics taking the full pass, then on +/// `fast`; checks that both leave the same document and that each refresh returned the same changed +/// texts. Returns whether each of `fast`'s refreshes checked only the changed layer trees. +fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut Session)) -> Vec { + let take = || cmd::inline::PASSES.with(|p| std::mem::take(&mut *p.borrow_mut())); + take(); + cmd::inline::FULL_PASS.set(true); + step(full); + cmd::inline::FULL_PASS.set(false); + let want = take(); + step(fast); + let got = take(); + assert_eq!(*full.doc().unwrap().doc, *fast.doc().unwrap().doc); + let ids = |passes: &[(bool, Vec)]| passes.iter().map(|(_, ids)| ids.clone()).collect::>(); + assert_eq!(ids(&got), ids(&want)); + assert!(want.iter().all(|(partial, _)| !partial)); + got.iter().map(|(partial, _)| *partial).collect() +} + +/// After an edit, inline graphics are checked again only in the layer trees the edit changed, and +/// the document and the changed texts are those of the full pass; a change to a symbol's art, its +/// natural size or anything else a symbol is measured with checks them all. +#[test] +fn refreshing_only_changed_trees_matches_the_full_pass() { + let setup = |s: &mut Session| { + circle_symbol(s, "Tap", 10.0); + circle_symbol(s, "Dot", 6.0); + let groups = rect_groups(s, 20, 10); + let id = text(s, "Tap here"); + s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap(); + // Type showing Dot inline becomes the opacity mask of a rectangle. + let masked = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 50, "height": 50})).unwrap()["id"].clone(); + let mask = text(s, "Dot"); + s.execute("text.insertInline", &json!({"id": mask.0, "at": 0, "symbol": "Dot"})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked, mask.0]})).unwrap(); + (groups, id) + }; + let (mut full, mut fast) = (session(), session()); + let (groups, id) = setup(&mut full); + assert_eq!(setup(&mut fast), (groups.clone(), id)); + let rect = groups[3][4].0; + let len = obj(&fast, id).plain_text().len(); + let only_changed = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| p); + let all = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| !p); + + // A rectangle beside 19 unchanged groups moves. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + }); + assert!(only_changed(&passes), "{passes:?}"); + // Type with an inline graphic is edited, gets a second one, and loses it again. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len, "insert": "!"})).unwrap(); + s.execute("text.insertInline", &json!({"id": id.0, "at": len, "symbol": "Dot"})).unwrap(); + s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len + INLINE_CHAR.len_utf8(), "insert": ""})).unwrap(); + }); + assert!(only_changed(&passes), "{passes:?}"); + // Dot's art is redefined: the type in the opacity mask follows it. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| redefine_as_wide_ellipse(s, "Dot")); + assert!(passes.contains(&false), "{passes:?}"); + // Tap's natural size changes, its art unchanged. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.edit("Size", |d, _| { + d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({ "Tap": [40.0, 20.0] })); + Ok(()) + }) + .unwrap(); + }); + assert!(all(&passes), "{passes:?}"); + let (b, want) = (inline_bounds(&obj(&fast, id)), fast.doc().unwrap().doc.symbol_art_bounds("Tap")); + assert!(b.is_some() && b == want, "{b:?} {want:?}"); + // 9-slice guides for Tap, its art unchanged. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("symbol.options", &json!({"name": "Tap", "nineSlice": true})).unwrap(); + }); + assert!(all(&passes), "{passes:?}"); + // Symbol editing mode, entered and left, a rectangle moved inside it. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("symbol.edit", &json!({"name": "Dot"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + }); + // Undo and redo, then edits after them. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap(); + }); + // Fonts scanned again, then another move. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("text.rescanFonts", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 1, "dy": 1})).unwrap(); + }); +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes in milliseconds: this thread's CPU time where Linux reports it, otherwise the +/// wall clock. +fn time_ms(f: impl FnOnce()) -> f64 { + let d = match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + }; + d.as_secs_f64() * 1000.0 +} + +/// The median, fastest and slowest of `runs`, as text. +fn spread(runs: &mut [f64]) -> String { + runs.sort_by(f64::total_cmp); + format!("{:>9.3} ({:.3}-{:.3})", runs[runs.len() / 2], runs[0], runs[runs.len() - 1]) +} + +/// Timings of the refresh of inline graphics after one rectangle moves, with the full pass and with +/// only the changed layer trees checked, in documents of 5,000, 50,000 and 200,000 rectangles in 100 +/// groups, with three symbols and one line of type showing one of them inline: the refresh alone, +/// on copies of the same edit, and the whole `object.move` command. 7 runs each, taking turns going +/// first. Ignored by default; it prints the median, fastest and slowest run and sets no bound on +/// them: `cargo test --release -p vectorcraft-engine --lib inline_refresh_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn inline_refresh_perf() { + const RUNS: usize = 7; + eprintln!("inline_refresh_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!("inline_refresh_perf: {:>7} {:<14} {:>28} {:>28}", "objects", "case", "full pass ms (min-max)", "changed trees ms (min-max)"); + for n in [5_000, 50_000, 200_000] { + let mut s = session(); + for name in ["A", "B", "C"] { + circle_symbol(&mut s, name, 10.0); + } + let groups = rect_groups(&mut s, 100, n / 100); + let id = text(&mut s, "Type"); + s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "B"})).unwrap(); + let rect = groups[50][7]; + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + // The refresh alone, after the same move made on a copy of the resolved document. + let resolved = s.doc().unwrap().inline_resolved.clone().unwrap(); + let before = resolved.0.clone(); + // The rectangle and the group and layer above it become new nodes, as a move makes them. + let mut after = (*before).clone(); + assert!(after.node_mut(rect).is_some()); + // Each run times EACH refreshes, or EACH commands, and gives the time of one. + const EACH: usize = 20; + let (mut full, mut partial) = (vec![], vec![]); + for run in 0..RUNS { + let (mut a, mut b) = (vec![after.clone(); EACH], vec![after.clone(); EACH]); + let mut go_full = || { + cmd::inline::FULL_PASS.set(true); + full.push( + time_ms(|| { + for d in &mut a { + cmd::inline::refresh(Some(&resolved), &before, d); + } + }) / EACH as f64, + ); + cmd::inline::FULL_PASS.set(false); + }; + let mut go_partial = || { + partial.push( + time_ms(|| { + for d in &mut b { + cmd::inline::refresh(Some(&resolved), &before, d); + } + }) / EACH as f64, + ); + }; + if run % 2 == 0 { + go_full(); + go_partial(); + } else { + go_partial(); + go_full(); + } + assert_eq!(a, b); + } + eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "refresh", spread(&mut full), spread(&mut partial)); + // The whole command, moving the rectangle back and forth. + let (mut full, mut partial) = (vec![], vec![]); + for run in 0..2 * RUNS { + let take_full = (run / 2) % 2 == run % 2; + cmd::inline::FULL_PASS.set(take_full); + let ms = time_ms(|| { + for i in 0..EACH { + let dx = if i % 2 == 0 { -1 } else { 1 }; + s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap(); + } + }) / EACH as f64; + cmd::inline::FULL_PASS.set(false); + if take_full { full.push(ms) } else { partial.push(ms) } + } + eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "object.move", spread(&mut full), spread(&mut partial)); + cmd::inline::PASSES.with(|p| p.borrow_mut().clear()); + } +} + #[test] fn create_outlines_turns_inline_graphics_into_symbol_instances() { let mut s = session(); diff --git a/crates/engine/src/tests/interpolate_handles.rs b/crates/engine/src/tests/interpolate_handles.rs new file mode 100644 index 0000000000..158eb6a5fb --- /dev/null +++ b/crates/engine/src/tests/interpolate_handles.rs @@ -0,0 +1,522 @@ +//! #7832: General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`). +//! With it on, a Direct Selection drag or an arrow-key nudge of selected anchors re-maps the +//! handles of each segment with one moved end, so the segment keeps its shape relative to its +//! ends. Off (the default), the handles of a moved anchor move with it and the others stay. + +use serde_json::json; +use vectorcraft_geom::{Anchor, PathData, Point}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use super::history; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn interpolate(s: &mut Session, on: bool) { + s.execute("prefs.set", &json!({"key": "interpolateControlPoints", "value": on})).unwrap(); +} + +fn path_of(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn anchor(s: &Session, id: NodeId, ai: usize) -> Anchor { + path_of(s, id).subpaths[0].anchors[ai] +} + +fn create(s: &mut Session, anchors: serde_json::Value) -> NodeId { + NodeId(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap()) +} + +/// A curve from (100, 100) to (300, 100) whose handles lie on its chord. +fn curve(s: &mut Session) -> NodeId { + create(s, json!([{"x": 100, "y": 100, "out": [150, 100]}, {"x": 300, "y": 100, "in": [250, 100]}])) +} + +fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value) { + s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": "set"})).unwrap(); +} + +/// A Direct Selection click on (`x`, `y`), then a drag from there to (`to_x`, `to_y`). +fn drag(s: &mut Session, (x, y): (f64, f64), (to_x, to_y): (f64, f64)) { + let v = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("directSelection", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, (x + to_x) / 2.0, (y + to_y) / 2.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to_x, to_y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to_x, to_y), v).unwrap(); +} + +#[test] +fn the_preference_is_off_by_default_and_the_handles_then_move_rigidly() { + let mut s = session(); + assert!(!s.prefs.interpolate_control_points); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.p, Point::new(120.0, 108.0)); + assert_eq!(a.h_out, Point::new(170.0, 108.0), "the moved anchor's handle moves with it"); + assert_eq!(b.h_in, Point::new(250.0, 100.0), "the other end's handle stays"); +} + +#[test] +fn a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let before = history(&s).0; + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + assert_eq!(history(&s).0, before + 1, "one undo step"); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + // The chord goes from (200, 0) to (180, -8): a scale by 0.9 and a turn, so the handles a + // quarter of the way from each end stay on the new chord, a quarter of the way along it. + assert_eq!(a.p, Point::new(120.0, 108.0)); + assert_eq!(a.h_in, a.p, "a retracted handle stays retracted"); + assert_eq!(a.h_out, Point::new(165.0, 106.0)); + assert_eq!(b.p, Point::new(300.0, 100.0)); + assert_eq!(b.h_in, Point::new(255.0, 102.0)); + assert_eq!(b.h_out, b.p); +} + +#[test] +fn a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + let original = path_of(&s, id); + drag(&mut s, (100.0, 100.0), (120.0, 108.0)); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.p, Point::new(120.0, 108.0)); + assert_eq!(a.h_out, Point::new(165.0, 106.0)); + assert_eq!(b.h_in, Point::new(255.0, 102.0)); + // One undo step puts the path back as it was before the drag. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id), original); +} + +#[test] +fn a_direct_selection_drag_with_the_preference_off_keeps_the_rigid_move() { + let mut s = session(); + let id = curve(&mut s); + drag(&mut s, (100.0, 100.0), (120.0, 108.0)); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.h_out, Point::new(170.0, 108.0)); + assert_eq!(b.h_in, Point::new(250.0, 100.0)); +} + +#[test] +fn a_segment_with_both_ends_moved_moves_rigidly() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 60]}, + {"x": 300, "y": 100, "in": [250, 60], "out": [350, 150]}, + {"x": 500, "y": 100, "in": [450, 140]}, + ]), + ); + select(&mut s, id, json!([[0, 0], [0, 1]])); + s.execute("object.nudge", &json!({"dx": 10, "dy": 5})).unwrap(); + let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2)); + assert_eq!((a.p, a.h_out), (Point::new(110.0, 105.0), Point::new(160.0, 65.0))); + assert_eq!((b.p, b.h_in), (Point::new(310.0, 105.0), Point::new(260.0, 65.0))); + // The segment to the unmoved third anchor is re-mapped: its chord goes from (200, 0) to + // (190, -5), a scale by 0.95 with a turn of -0.025 per unit. + close(b.h_out, Point::new(358.75, 151.25)); + close(c.h_in, Point::new(453.5, 139.25)); + assert_eq!(c.p, Point::new(500.0, 100.0)); +} + +fn close(p: Point, q: Point) { + assert!((p.x - q.x).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9, "{p:?} is not {q:?}"); +} + +/// A closed square from (100, 100) to (300, 300) whose handles lie on its sides, a quarter of +/// the way along. +fn square(s: &mut Session) -> NodeId { + let anchors = json!([ + {"x": 100, "y": 100, "in": [100, 150], "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [300, 150]}, + {"x": 300, "y": 300, "in": [300, 250], "out": [250, 300]}, + {"x": 100, "y": 300, "in": [150, 300], "out": [100, 250]}, + ]); + NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": true })).unwrap()["id"].as_u64().unwrap()) +} + +#[test] +fn moving_the_first_anchor_of_a_closed_path_re_maps_the_closing_segment_too() { + let mut s = session(); + interpolate(&mut s, true); + let id = square(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 0, "dy": -200})).unwrap(); + let (a, b, c, d) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2), anchor(&s, id, 3)); + assert_eq!(a.p, Point::new(100.0, -100.0)); + // The segment to the second anchor: its chord goes from (200, 0) to (200, 200). + close(a.h_out, Point::new(150.0, -50.0)); + close(b.h_in, Point::new(250.0, 50.0)); + // The closing segment from the fourth anchor: its chord goes from (0, -200) to (0, -400). + close(d.h_out, Point::new(100.0, 200.0)); + close(a.h_in, Point::new(100.0, 0.0)); + // The segment between the third and fourth anchors is not beside the moved anchor. + assert_eq!((c.h_out, d.h_in), (Point::new(250.0, 300.0), Point::new(150.0, 300.0))); + assert_eq!((b.h_out, c.h_in), (Point::new(300.0, 150.0), Point::new(300.0, 250.0))); +} + +#[test] +fn moving_the_last_anchor_of_an_open_path_re_maps_only_the_segment_before_it() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [350, 50]}, + {"x": 500, "y": 100, "in": [450, 100], "out": [550, 50]}, + ]), + ); + select(&mut s, id, json!([[0, 2]])); + s.execute("object.nudge", &json!({"dx": 0, "dy": 200})).unwrap(); + let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2)); + assert_eq!(c.p, Point::new(500.0, 300.0)); + // The chord from the second (corner) anchor goes from (200, 0) to (200, 200). + close(b.h_out, Point::new(400.0, 100.0)); + close(c.h_in, Point::new(450.0, 250.0)); + // The last anchor's own outgoing handle leads to no segment and moves with it. + assert_eq!(c.h_out, Point::new(550.0, 250.0)); + assert_eq!((a.h_out, b.h_in), (Point::new(150.0, 100.0), Point::new(250.0, 100.0))); +} + +#[test] +fn move_and_transform_of_anchors_re_map_the_handles_in_one_undo_step() { + for (cmd, params) in [("object.move", json!({"dx": 20, "dy": 8})), ("object.transform", json!({"matrix": [1, 0, 0, 1, 20, 8], "anchors": true}))] + { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let (before, original) = (history(&s).0, path_of(&s, id)); + s.execute(cmd, ¶ms).unwrap(); + assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step"); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}"); + close(a.h_out, Point::new(165.0, 106.0)); + close(b.h_in, Point::new(255.0, 102.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id), original, "{cmd}: undone"); + } +} + +#[test] +fn set_bounds_and_guide_move_of_anchors_follow_the_preference_and_the_param() { + for (pref, param, re_mapped) in [(false, None, false), (true, None, true), (true, Some(false), false), (false, Some(true), true)] { + for cmd in ["object.setBounds", "guide.move"] { + let mut s = session(); + interpolate(&mut s, pref); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let mut params = if cmd == "object.setBounds" { + json!({"x": 120, "y": 108}) + } else { + let g = s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap()["index"].as_u64().unwrap(); + s.execute("guide.select", &json!({"indexes": [g], "toggle": true})).unwrap(); + json!({"dx": 20, "dy": 8}) + }; + if let Some(on) = param { + params["interpolate"] = json!(on); + } + let (before, original) = (history(&s).0, path_of(&s, id)); + s.execute(cmd, ¶ms).unwrap(); + assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step"); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}"); + if re_mapped { + close(a.h_out, Point::new(165.0, 106.0)); + close(b.h_in, Point::new(255.0, 102.0)); + } else { + assert_eq!((a.h_out, b.h_in), (Point::new(170.0, 108.0), Point::new(250.0, 100.0)), "{cmd}, pref {pref}, param {param:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id), original, "{cmd}: undone"); + } + } + let mut s = session(); + let id = curve(&mut s); + // Both anchors, so that a new width scales them and does not only move them. + select(&mut s, id, json!([[0, 0], [0, 1]])); + s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + let original = path_of(&s, id); + for (cmd, params) in [ + ("object.setBounds", json!({"x": 120, "interpolate": "yes"})), + ("object.setBounds", json!({"width": 50, "interpolate": 1})), + ("guide.move", json!({"dx": 1, "interpolate": "yes"})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}"); + } + assert_eq!(path_of(&s, id), original); + // With only guides selected, guide.move rejects the value too and leaves the guide. + s.execute("select.none", &json!({})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let e = s.execute("guide.move", &json!({"dx": 1, "interpolate": "yes"})).unwrap_err().to_string(); + assert!(e.contains("`interpolate` must be true or false"), "guide.move: {e}"); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].pos, 50.0); +} + +#[test] +fn the_interpolate_param_overrides_the_preference_and_rejects_other_values() { + for (pref, param, re_mapped) in [(true, false, false), (false, true, true)] { + let mut s = session(); + interpolate(&mut s, pref); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("path.moveAnchors", &json!({"dx": 20, "dy": 8, "interpolate": param})).unwrap(); + let b = anchor(&s, id, 1); + assert_eq!(b.h_in != Point::new(250.0, 100.0), re_mapped, "pref {pref}, param {param}: {:?}", b.h_in); + } + let mut s = session(); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let original = path_of(&s, id); + for (cmd, params) in [ + ("path.moveAnchors", json!({"dx": 1, "dy": 0, "interpolate": "yes"})), + ("object.nudge", json!({"dx": 1, "dy": 0, "interpolate": "yes"})), + ("object.move", json!({"dx": 1, "dy": 0, "interpolate": "yes"})), + ("object.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "anchors": true, "interpolate": 1})), + ("object.transformAgain", json!({"interpolate": "yes"})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}"); + } + assert_eq!(path_of(&s, id), original); +} + +#[test] +fn a_replayed_move_re_maps_the_handles_as_it_did_whatever_the_preference_is_then() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let start = s.journal.len(); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + let moved = path_of(&s, id); + let (cmd, params) = s.journal.since(start).last().cloned().unwrap(); + assert_eq!(params["interpolate"], json!(true), "{cmd}: journaled"); + // Undo, turn the preference off and play the journal entry again. + s.execute("edit.undo", &json!({})).unwrap(); + interpolate(&mut s, false); + select(&mut s, id, json!([[0, 0]])); + s.replay(&cmd, ¶ms).unwrap(); + assert_eq!(path_of(&s, id), moved); +} + +#[test] +fn a_saved_step_without_interpolate_moves_the_handles_rigidly_whatever_the_preference() { + // A step recorded before the preference existed has no `interpolate`; with the preference on, + // it still plays as it did when it was recorded. + for cmd in ["path.moveAnchors", "object.nudge", "object.move"] { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.replay(cmd, &json!({"dx": 1, "dy": 1})).unwrap(); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_ne!(a.p, Point::new(100.0, 100.0), "{cmd}: the anchor moves"); + assert_eq!((a.h_out.x - a.p.x, a.h_out.y - a.p.y), (50.0, 0.0), "{cmd}: the moved anchor's handle moves with it"); + assert_eq!(b.h_in, Point::new(250.0, 100.0), "{cmd}: the other end's handle stays"); + // Run directly, the same params follow the preference. + s.execute(cmd, &json!({"dx": 1, "dy": 1})).unwrap(); + assert_ne!(anchor(&s, id, 1).h_in, Point::new(250.0, 100.0), "{cmd}: executed, the handles are re-mapped"); + } +} + +#[test] +fn transform_again_keeps_the_setting_its_move_used() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + interpolate(&mut s, false); + s.execute("object.transformAgain", &json!({})).unwrap(); + let mut t = session(); + interpolate(&mut t, true); + let other = curve(&mut t); + select(&mut t, other, json!([[0, 0]])); + t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + assert_eq!(path_of(&s, id), path_of(&t, other)); +} + +#[test] +fn a_segment_whose_ends_are_at_the_same_place_moves_rigidly() { + let mut s = session(); + interpolate(&mut s, true); + let id = create(&mut s, json!([{"x": 100, "y": 100, "out": [150, 50]}, {"x": 100, "y": 100, "in": [50, 150]}])); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 10, "dy": 0})).unwrap(); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!((a.p, a.h_out), (Point::new(110.0, 100.0), Point::new(160.0, 50.0))); + assert_eq!((b.p, b.h_in), (Point::new(100.0, 100.0), Point::new(50.0, 150.0))); +} + +#[test] +fn a_move_onto_the_other_end_moves_the_handles_rigidly() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 200, "dy": 0})).unwrap(); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!((a.p, a.h_out), (Point::new(300.0, 100.0), Point::new(350.0, 100.0))); + assert_eq!(b.h_in, Point::new(250.0, 100.0)); +} + +#[test] +fn a_nudge_of_zero_with_the_preference_on_records_no_undo_step() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let (before, original) = (history(&s), path_of(&s, id)); + s.execute("object.nudge", &json!({"dx": 0, "dy": 0})).unwrap(); + assert_eq!(history(&s), before); + assert_eq!(path_of(&s, id), original); +} + +#[test] +fn a_smooth_anchor_keeps_its_handles_in_line() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true}, + {"x": 500, "y": 100, "in": [450, 100]}, + ]), + ); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap(); + let b = anchor(&s, id, 1); + assert_eq!(b.p, Point::new(300.0, 100.0)); + // The segment to the third anchor did not move, so its handle stays where it was. + assert_eq!(b.h_out, Point::new(350.0, 100.0)); + // The incoming handle grows with the chord from the moved anchor (from 200 to 100√5) and + // turns back in line with the outgoing one. + assert_eq!(b.h_in.y, 100.0, "in line: {:?}", b.h_in); + assert!((300.0 - b.h_in.x - 25.0 * 5f64.sqrt()).abs() < 1e-9, "{:?}", b.h_in); +} + +#[test] +fn a_moved_smooth_anchor_keeps_a_retracted_handle_exactly_retracted() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 0, "y": 100, "out": [50, 100]}, + {"x": 200, "y": 100, "in": [200, 100], "out": [250, 150], "smooth": true}, + {"x": 400, "y": 100, "in": [350, 100]}, + ]), + ); + select(&mut s, id, json!([[0, 1]])); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8.1})).unwrap(); + let b = anchor(&s, id, 1); + assert_eq!(b.p, Point::new(220.0, 108.1)); + // Re-mapping the retracted handle by its segment's map would leave it a rounding error away + // from the anchor, and lining the handles up would then turn the outgoing one by that error. + assert_eq!(b.h_in, b.p, "the retracted handle stays retracted"); + // The chord to the third anchor goes from (200, 0) to (180, -8.1). + close(b.h_out, Point::new(267.025, 151.075)); +} + +#[test] +fn transform_again_repeats_a_move_with_the_handles_re_mapped() { + let twice = |again: bool| { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + if again { + s.execute("object.transformAgain", &json!({})).unwrap(); + } else { + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + } + path_of(&s, id) + }; + let (repeated, nudged) = (twice(true), twice(false)); + assert_eq!(repeated.subpaths[0].anchors[0].p, Point::new(140.0, 116.0)); + assert_eq!(repeated, nudged); +} + +#[test] +fn a_transform_that_scales_by_a_hair_still_scales_the_anchors() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let k = 1.000_000_000_5; + s.execute("object.transform", &json!({"matrix": [k, 0, 0, 1, 0, 0], "anchors": true})).unwrap(); + let a = anchor(&s, id, 0); + assert_eq!(a.p, Point::new(100.0 * k, 100.0)); + assert_eq!(a.h_out, Point::new(150.0 * k, 100.0)); +} + +#[test] +fn a_smooth_anchor_whose_re_mapped_handles_point_the_same_way_moves_them_with_it() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true}, + {"x": 500, "y": 100, "in": [450, 100]}, + ]), + ); + select(&mut s, id, json!([[0, 1]])); + s.execute("object.nudge", &json!({"dx": 300, "dy": 0})).unwrap(); + // Both chords re-map their handle to the left of the anchor, which has no direction between + // them: both handles move with the anchor, as with the preference off. + let b = anchor(&s, id, 1); + assert_eq!(b.p, Point::new(600.0, 100.0)); + assert_eq!(b.h_out, Point::new(650.0, 100.0)); + assert_eq!(b.h_in, Point::new(550.0, 100.0)); +} + +#[test] +fn a_smooth_anchor_between_two_re_mapped_segments_keeps_its_handles_in_line() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true}, + {"x": 500, "y": 100, "in": [450, 100]}, + ]), + ); + select(&mut s, id, json!([[0, 1]])); + s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap(); + let b = anchor(&s, id, 1); + let (v_in, v_out) = (b.h_in - b.p, b.h_out - b.p); + assert_eq!(b.p, Point::new(300.0, 0.0)); + // The two chords turn by the same angle in opposite directions, so the handles point along + // the mean of the two: across, at the length each chord gives them. + assert!(v_in.cross(v_out).abs() < 1e-9, "the handles stay in line: {:?} {:?}", b.h_in, b.h_out); + assert!(v_in.dot(v_out) < 0.0, "on opposite sides of the anchor"); + assert!(v_out.y.abs() < 1e-9 && v_out.x > 0.0, "{:?}", b.h_out); + assert!((v_out.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9 && (v_in.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9); +} diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index f6b35716f6..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() } @@ -213,6 +390,117 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() { assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]); } +/// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty +/// third layer `e`. +#[derive(Clone, Copy)] +struct Column { + layer: NodeId, + sub: NodeId, + a: NodeId, + g: NodeId, + b: NodeId, + c: NodeId, + o: NodeId, + e: NodeId, +} + +fn column_start() -> (Session, Column) { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + run(&mut s, "layer.setCurrent", json!({"id": layer.0})); + let other = id(&run(&mut s, "layer.new", json!({}))); + let o = rect(&mut s, 200.0); + let e = id(&run(&mut s, "layer.new", json!({}))); + run(&mut s, "select.none", json!({})); + let top: Vec = s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert!(top.contains(&other) && top.contains(&e) && parent(&s, o) == Some(other), "{top:?}"); + (s, Column { layer, sub, a, g, b, c, o, e }) +} + +type Prep = dyn Fn(&mut Session, Column); + +/// A Shift-click in the selection column of `row` (whose art is `art`) after `prep` gives the +/// same selection, reply, current layer, highlighted rows and revision as removing or adding each +/// id of `art` one at a time. Returns the session the click ran in. +fn shift_column_matches_each_id(prep: &Prep, row: impl Fn(Column) -> NodeId, art: impl Fn(Column) -> Vec) -> (Session, Column) { + let (mut new, t) = column_start(); + prep(&mut new, t); + let row = row(t); + let before = new.doc().unwrap().selection.clone(); + let reply = run(&mut new, "layer.selectAll", json!({"id": row.0, "add": true})); + let (mut old, t) = column_start(); + prep(&mut old, t); + let ids = art(t); + let st = old.doc().unwrap(); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + old.select(|_, sel| { + for i in &ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } + }) + .unwrap(); + old.doc_mut().unwrap().layer_rows = rows; + let (n, o) = (new.doc().unwrap(), old.doc().unwrap()); + assert_eq!(n.selection, o.selection, "row {row:?} from {before:?}"); + assert_eq!(ids_sel(&reply), o.selection.objects); + assert_eq!(n.active_layer, o.active_layer); + assert_eq!(n.highlighted_rows(), o.highlighted_rows()); + assert_eq!(n.revision, o.revision); + assert_eq!(undos(&new), undos(&old)); + (new, t) +} + +#[test] +fn a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id() { + // `o` outside the layer is selected first and is the key object and the target; `a` is + // selected by one anchor, which is the key anchor. + let partly: &Prep = &|s, t| { + run(s, "layer.setCurrent", json!({"id": t.sub.0})); + let sel = &mut s.doc_mut().unwrap().selection; + sel.objects = vec![t.o, t.a]; + sel.anchors.insert(t.a, [(0, 1)].into()); + sel.key = Some(t.o); + sel.key_anchor = Some((t.a, (0, 1))); + sel.target = Some(t.o); + }; + let layer_art = |t: Column| vec![t.c, t.a, t.g]; + // Some of the layer's art is selected: the rest is added after what was selected. + let (s, t) = shift_column_matches_each_id(partly, |t| t.layer, layer_art); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![t.o, t.a, t.c, t.g]); + assert_eq!(sel.anchors.len(), 1, "the picked anchor stays picked"); + assert!(sel.target.is_none()); + // All of it is selected, `a` as the key object: it is removed, with its anchors, key and key + // anchor. + let all: &Prep = &|s, t| { + partly(s, t); + let sel = &mut s.doc_mut().unwrap().selection; + sel.objects.extend([t.c, t.g]); + sel.key = Some(t.a); + }; + let (s, t) = shift_column_matches_each_id(all, |t| t.layer, layer_art); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![t.o]); + assert!(sel.anchors.is_empty() && sel.key.is_none() && sel.key_anchor.is_none()); + // An object row, a group row and an empty layer's row. + shift_column_matches_each_id(all, |t| t.c, |t| vec![t.c]); + shift_column_matches_each_id(partly, |t| t.g, |t| vec![t.g]); + shift_column_matches_each_id(partly, |t| t.e, |_| vec![]); + // A locked sublayer's row, and rows outside and inside the isolated group. + let locked: &Prep = &|s, t| { + partly(s, t); + run(s, "layer.setProps", json!({"id": t.sub.0, "locked": true})); + }; + shift_column_matches_each_id(locked, |t| t.sub, |_| vec![]); + let isolated: &Prep = &|s, t| { + partly(s, t); + s.doc_mut().unwrap().isolation = Some(t.g); + }; + shift_column_matches_each_id(isolated, |t| t.c, |_| vec![]); + shift_column_matches_each_id(isolated, |t| t.b, |t| vec![t.b]); +} + fn ids_sel(v: &Value) -> Vec { v["selected"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } @@ -481,6 +769,54 @@ fn new_layers_go_below_the_current_one_and_sublayers_under_the_contents() { assert_eq!(children(&s, layer), vec![front, under, back]); } +/// In Draw Behind a new layer goes directly below the current layer, at its level, in one undo +/// step; `top` and `below` keep their meaning, Draw Inside and Draw Normal keep it above, and new +/// sublayers are not affected. +#[test] +fn new_layers_go_below_the_current_one_in_draw_behind() { + let mut s = session(); + let (layer, sub, a, g, _, c) = tree(&mut s); + run(&mut s, "view.drawMode", json!({"mode": "behind"})); + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let before = undos(&s); + let n = id(&run(&mut s, "layer.new", json!({}))); + assert_eq!(children(&s, layer), vec![c, n, sub], "a sublayer directly below the current sublayer"); + assert_eq!(undos(&s), before + 1); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![n]); + assert_eq!(s.doc().unwrap().current_layer(), Some(n)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(children(&s, layer), vec![c, sub]); + // The Create New Layer button sends `top: false` for a plain click: still below. + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let n = id(&run(&mut s, "layer.new", json!({"top": false}))); + assert_eq!(children(&s, layer), vec![c, n, sub]); + run(&mut s, "edit.undo", json!({})); + // At the top level, and with options. + run(&mut s, "layer.setCurrent", json!({"id": layer.0})); + let back = id(&run(&mut s, "layer.new", json!({"name": "Back", "locked": true}))); + let order = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + assert_eq!(order(&s), vec![back, layer]); + assert!(node(&s, back).locked); + // `top` and `below` win over the drawing mode. + let top = id(&run(&mut s, "layer.new", json!({"top": true}))); + assert_eq!(order(&s), vec![back, layer, top]); + let below = id(&run(&mut s, "layer.new", json!({"below": true}))); + assert_eq!(order(&s), vec![back, layer, below, top]); + assert!(s.execute("layer.new", &json!({"top": true, "below": true})).is_err()); + // New sublayers still go on top of the parent's contents. + let inner = id(&run(&mut s, "layer.newSublayer", json!({"parent": sub.0}))); + assert_eq!(children(&s, sub), vec![a, g, inner]); + // Draw Inside and Draw Normal put it above. + run(&mut s, "select.set", json!({"ids": [c.0]})); + for mode in ["inside", "normal"] { + run(&mut s, "view.drawMode", json!({"mode": mode})); + assert_eq!(s.draw_mode, if mode == "inside" { DrawMode::Inside } else { DrawMode::Normal }); + run(&mut s, "layer.setCurrent", json!({"id": back.0})); + let n = id(&run(&mut s, "layer.new", json!({}))); + assert_eq!(s.doc().unwrap().doc.layers[1].id, n, "{mode}"); + } +} + #[test] fn rows_move_above_below_and_into_layers_and_groups() { let mut s = session(); @@ -643,6 +979,45 @@ fn alt_drag_copies_rows_and_the_selected_art_moves_between_layers() { assert_eq!(s.doc().unwrap().selection.objects, vec![a, g], "it stays selected"); } +/// #8237: a copy may go above or below a row it copies, so a lone layer, the top layer dragged up +/// and the bottom one dragged down can be copied. A move there, or a copy inside the row, is still +/// refused. +#[test] +fn a_copy_goes_above_or_below_a_row_it_copies() { + let mut s = session(); + let layers = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let [only] = layers(&s)[..] else { panic!("one layer") }; + for place in ["above", "below", "inside"] { + assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": place})).is_err(), "a move {place} itself"); + } + assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": "inside", "copy": true})).is_err()); + assert_eq!(layers(&s), vec![only], "nothing changed"); + let above = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "above", "copy": true}))); + assert_eq!(layers(&s), vec![only, above[0]], "the copy above the original"); + let below = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "below", "copy": true}))); + assert_eq!(layers(&s), vec![below[0], only, above[0]], "and one below it"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layers(&s), vec![only, above[0]], "each copy is one undo step"); +} + +/// #8237 review: rows that hold an object can't sit beside a top-level layer, so copied beside a +/// top-level layer among them they would go inside it: a copy of that layer inside itself. Refused, +/// and nothing changes. +#[test] +fn a_copy_with_objects_beside_a_copied_top_level_layer_is_refused() { + let mut s = session(); + let bottom = s.doc().unwrap().doc.layers[0].id; + let other = id(&run(&mut s, "layer.new", json!({}))); + let r = rect(&mut s, 0.0); + assert_eq!(s.doc().unwrap().doc.parent_of(r), Some(other), "the rectangle is in the other layer"); + let count = s.doc().unwrap().doc.node_count(); + for place in ["above", "below"] { + let p = json!({"ids": [bottom.0, r.0], "target": bottom.0, "place": place, "copy": true}); + assert!(s.execute("layer.move", &p).is_err(), "{place}: the layer's copy would go inside it"); + } + assert_eq!(s.doc().unwrap().doc.node_count(), count, "nothing copied"); +} + /// The selected art in rows dragged into a hidden layer or group is deselected, the key object /// included. Undo puts the rows back and selects the art again. #[test] @@ -904,6 +1279,75 @@ 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] +fn locate_layer_highlights_the_layer_holding_the_object() { + let mut s = session(); + let (layer, sub, _, g, b, c) = tree(&mut s); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let r = run(&mut s, "layer.locate", json!({"layersOnly": true})); + assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]); + assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row"); + s.doc_mut().unwrap().locate_reveal = None; + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, "layer.locate", json!({"layersOnly": true})); + assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]); + let r = run(&mut s, "layer.locate", json!({"id": sub.0, "layersOnly": true})); + assert_eq!((r["id"].clone(), r["objectId"].clone()), (json!(sub.0), json!(sub.0)), "a sublayer locates itself"); + // Off, the object's own row is highlighted, as before. + assert_eq!(run(&mut s, "layer.locate", json!({"id": g.0, "layersOnly": false})), json!({"id": g.0, "ancestry": [layer.0, sub.0, g.0]})); + // Bad input changes nothing. + for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] { + assert!(s.execute("layer.locate", &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}"); + assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}"); + } + run(&mut s, "select.none", json!({})); + assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected"); +} + #[test] fn the_clipping_mask_button_acts_on_the_highlighted_group() { let mut s = session(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 87dd7453f6..313d573206 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2542,34 +2542,6 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() { } } -/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first -/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does -/// not refuse it, and one in the first asset does. -#[test] -fn confined_single_file_pdf_checks_the_document_it_carries() { - use crate::file_access::{AutomationRoots, confine}; - - let away = Folder::new("single-pdf-away"); - let home = Folder::new("single-pdf-home"); - let photo = away.file("photo.png"); - write(&photo, &png(60, 30, RED)); - let mut s = session(); - let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); - let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); - let placed = place(&mut s, &photo); - let mut assets = vec![]; - for id in [rect, placed] { - assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap()); - } - let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); - let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); - let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}")); - assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}"); - let reversed = [assets[1], assets[0]]; - let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string(); - assert!(e.contains("a linked image file is outside the read roots"), "{e}"); -} - /// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with /// Preserve Editing, a package's document) carry the document without the Export for Screens /// folder when it is outside the read roots, with the other export settings and the art; the open diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index 2aa182c8b9..dc37c49761 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -1629,9 +1629,9 @@ fn cmyk_mesh(create: Value) -> (Session, NodeId) { (s, a) } -/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` operands, and the -/// corner colours of its gradient meshes, which are patch shadings, as PDF import reads them -/// back), and its warnings. +/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` and DeviceCMYK +/// `c m y k k` operands, and the corner colours of its gradient meshes, which are patch shadings, +/// as PDF import reads them back), and its warnings. fn pdf_fill_colours(s: &mut Session) -> (Vec>, Vec) { let v = s.execute("document.exportPdf", &json!({"standard": "pdfX4", "compression": {"compressText": false}})).unwrap(); let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); @@ -1646,6 +1646,11 @@ fn pdf_fill_colours(s: &mut Session) -> (Vec>, Vec) { if !nums.is_empty() { out.push(nums.into_iter().rev().collect()); } + } else if *w == "k" { + let nums: Vec = words[..i].iter().rev().take(4).map_while(|x| x.parse().ok()).collect(); + if nums.len() == 4 { + out.push(nums.into_iter().rev().collect()); + } } } } diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 1797ce27fe..e372467603 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -392,6 +392,67 @@ fn an_ellipse_takes_pie_angles_and_inverts() { assert!(s.execute("object.setLiveShape", &json!({"pieStart": "half"})).is_err()); } +/// Constrain Pie Angle (`constrainPie`): a new Pie Start or End Angle moves the other angle by as +/// much, so each selected ellipse keeps its own span, across 0° too; a whole ellipse stays whole; +/// after Invert Pie the inverted span is kept; one undo step for all of them; the angle each +/// already has records nothing; and `constrainPie` with both angles, with neither, with Invert Pie +/// or as text is an error that changes nothing. +#[test] +fn constrain_pie_keeps_each_ellipses_span() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let [a, b, c] = [0, 100, 200].map(|y| id(s.execute("shape.ellipse", &json!({"x": 0, "y": y, "width": 200, "height": 80})).unwrap())); + run(&mut s, json!({"ids": [a.0], "pieStart": 300, "pieEnd": 60})); + run(&mut s, json!({"ids": [b.0], "pieStart": 0, "pieEnd": 90})); + let pies = |s: &Session| { + [a, b, c].map(|i| match &s.doc().unwrap().doc.node(i).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => match &**l { + LiveShape::Ellipse { pie, .. } => *pie, + k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }) + }; + let near = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = undo(&s); + // 300° to 60° spans 120°, through 0°; 0° to 90° spans 90°; the third ellipse is whole. + run(&mut s, json!({"ids": [a.0, b.0, c.0], "pieStart": 350, "constrainPie": true})); + let [pa, pb, pc] = pies(&s); + assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}"); + assert!(near(pc, (350.0, 350.0)), "{pc:?}"); + assert_eq!(s.doc().unwrap().doc.node(c).unwrap().path_data().unwrap().anchor_count(), 4, "the whole ellipse stays whole"); + assert_eq!(undo(&s), n + 1, "one undo step"); + run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 20, "constrainPie": true})); + let [pa, pb, _] = pies(&s); + assert!(near(pa, (260.0, 20.0)) && near(pb, (290.0, 20.0)), "{pa:?} {pb:?}"); + let n = undo(&s); + run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 380, "constrainPie": true})); + assert_eq!(undo(&s), n, "the end each already has: no undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + let [pa, pb, _] = pies(&s); + assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}"); + // Inverted, 80° to 350° spans 270°, and a linked edit keeps that. + run(&mut s, json!({"ids": [b.0], "invertPie": true})); + run(&mut s, json!({"ids": [b.0], "pieStart": 0, "constrainPie": true})); + assert!(near(pies(&s)[1], (0.0, 270.0)), "{:?}", pies(&s)[1]); + let before = (undo(&s), pies(&s)); + for (p, want) in [ + (json!({"ids": [b.0], "pieStart": 10, "pieEnd": 20, "constrainPie": true}), "needs one of"), + (json!({"ids": [b.0], "constrainPie": true}), "needs one of"), + (json!({"ids": [b.0], "pieStart": 10, "constrainPie": true, "invertPie": true}), "needs one of"), + (json!({"ids": [b.0], "pieStart": 10, "constrainPie": "yes"}), "`constrainPie` must be true or false"), + ] { + let r = s.execute("object.setLiveShape", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}"); + assert_eq!((undo(&s), pies(&s)), before, "{p}"); + } + // Off, each angle is set on its own, as before. + run(&mut s, json!({"ids": [b.0], "pieStart": 90, "constrainPie": false})); + assert!(near(pies(&s)[1], (90.0, 270.0)), "{:?}", pies(&s)[1]); +} + /// Invert Pie and Make Sides Equal given as text or as another value that is not true or false are /// an error naming the key: the ellipse's pie, the polygon and the undo history stay as they were. /// True makes the change, and false and null leave the shape as it is. @@ -524,6 +585,107 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() { } } +/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees +/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the +/// length applies before the angle, every selected line takes them in one undo step, and a value +/// that changes nothing records none. +#[test] +fn a_line_takes_its_length_and_angle() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let line = |s: &mut Session, a: (f64, f64), b: (f64, f64)| { + NodeId(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap()["id"].as_u64().unwrap()) + }; + let id = line(&mut s, (100.0, 100.0), (200.0, 100.0)); + let ends = |s: &Session, id: NodeId| match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { live: Some(l), path, .. } => { + let LiveShape::Line { a, b } = **l else { panic!("{l:?}") }; + assert_eq!(*path, l.to_path(), "the path follows the line"); + (a.x, a.y, b.x, b.y) + } + k => panic!("{k:?}"), + }; + let near = |got: (f64, f64, f64, f64), want: (f64, f64, f64, f64)| { + assert!([got.0 - want.0, got.1 - want.1, got.2 - want.2, got.3 - want.3].iter().all(|d| d.abs() < 1e-9), "{got:?} ≠ {want:?}") + }; + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + run(&mut s, json!({"lineLength": 50})); + near(ends(&s, id), (100.0, 100.0, 150.0, 100.0)); + // 90° points up the page. + run(&mut s, json!({"lineAngle": 90})); + near(ends(&s, id), (125.0, 125.0, 125.0, 75.0)); + let n = steps(&s); + for same in [json!({"lineAngle": 450}), json!({"lineAngle": -270}), json!({"lineLength": 50}), json!({"lineLength": 50, "lineAngle": 90})] { + run(&mut s, same.clone()); + assert_eq!(steps(&s), n, "{same} records no undo step"); + } + near(ends(&s, id), (125.0, 125.0, 125.0, 75.0)); + run(&mut s, json!({"lineLength": 20, "lineAngle": 0})); + near(ends(&s, id), (115.0, 115.0, 135.0, 115.0)); + assert_eq!(steps(&s), n + 1, "both in one step"); + run(&mut s, json!({"lineAngle": 180})); + near(ends(&s, id), (135.0, 115.0, 115.0, 115.0)); + run(&mut s, json!({"lineAngle": -90})); + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + let LiveShape::Line { .. } = s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap() else { panic!("still live") }; + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap().line_angle(), Some(270.0)); + // Several lines: each keeps its own first end, in one undo step. + let other = line(&mut s, (0.0, 0.0), (0.0, 40.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [id.0, other.0], "lineLength": 10})); + near(ends(&s, id), (125.0, 105.0, 125.0, 115.0)); + near(ends(&s, other), (0.0, 0.0, 0.0, 10.0)); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + near(ends(&s, other), (0.0, 0.0, 0.0, 40.0)); + // Bad values, and a line that would reach past the coordinate limit, change neither line. + let far = line(&mut s, (3_900_000.0, 0.0), (3_900_100.0, 0.0)); + let n = steps(&s); + for bad in [ + json!({"ids": [id.0], "lineLength": 0}), + json!({"ids": [id.0], "lineLength": -3}), + json!({"ids": [id.0], "lineLength": "long"}), + json!({"ids": [id.0], "lineAngle": "up"}), + json!({"ids": [id.0], "lineLength": 1e300}), + json!({"ids": [id.0, far.0], "lineLength": 200_000}), + ] { + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + assert_eq!(steps(&s), n, "{bad}"); + } + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + near(ends(&s, far), (3_900_000.0, 0.0, 3_900_100.0, 0.0)); + // A length past the coordinate limit is fine while both ends stay inside it. + let wide = line(&mut s, (-3_500_000.0, 0.0), (3_500_000.0, 0.0)); + run(&mut s, json!({"ids": [wide.0], "lineLength": 6_000_000})); + near(ends(&s, wide), (-3_500_000.0, 0.0, 2_500_000.0, 0.0)); + // A line whose ends meet reads 0°: an angle leaves it as it is, and a length points it right. + let dot = line(&mut s, (10.0, 10.0), (10.0, 10.0)); + assert_eq!(s.doc().unwrap().doc.node(dot).unwrap().live_shape().unwrap().line_angle(), Some(0.0)); + let n = steps(&s); + run(&mut s, json!({"lineAngle": 45})); + assert_eq!(steps(&s), n); + run(&mut s, json!({"lineLength": 30})); + near(ends(&s, dot), (10.0, 10.0, 40.0, 10.0)); + // A very short length is applied. + let speck = line(&mut s, (20.0, 20.0), (20.0, 20.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [speck.0], "lineLength": 1e-12})); + assert_eq!(steps(&s), n + 1, "a length of 1e-12 pt is a change"); + assert!(ends(&s, speck).2 > 20.0, "{:?}", ends(&s, speck)); + // A length so short that the rounded ends do not move records no undo step. + let dust = line(&mut s, (20.0, 20.0), (20.0, 20.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [dust.0], "lineLength": 1e-20})); + assert_eq!(steps(&s), n, "a length of 1e-20 pt changes nothing"); + near(ends(&s, dust), (20.0, 20.0, 20.0, 20.0)); + // Other live shapes ignore the line params. + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + let n = steps(&s); + run(&mut s, json!({"ids": [rect.0], "lineLength": 30, "lineAngle": 45})); + assert_eq!(steps(&s), n); +} + #[test] fn relative_corner_rounding_keeps_fraction_on_resize() { let (mut s, id) = session(); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1faeaa76ad..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 @@ -4473,6 +4652,58 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() { assert_eq!(selected(&s), vec![g]); } +/// Exit Isolation Mode on an isolated sublayer isolates its parent layer and selects the sublayer, one +/// layer per call, without an undo step; from the top-level layer it leaves isolation mode. `all: true` +/// leaves from any depth, a hidden parent layer is not isolated (the call leaves), and a group in a +/// sublayer still leaves in one call. +#[test] +fn exit_isolation_goes_up_one_layer_from_a_sublayer() { + let mut s = session(); + let top = s.doc().unwrap().doc.layers[0].id; + let mid = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()); + let deep = id_of(&s.execute("layer.newSublayer", &json!({"parent": mid.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": deep.0})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + let isolation = |s: &Session| s.doc().unwrap().isolation; + let exit = |s: &mut Session, p: Value| s.execute("object.exitIsolation", &p).unwrap(); + + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + let before = history(&s); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (Some(mid), vec![deep]), "up from the deepest sublayer"); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (Some(top), vec![mid]), "up from the middle sublayer"); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![top]), "out from the top-level layer"); + assert_eq!(history(&s), before, "no undo step"); + + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + exit(&mut s, json!({"all": true})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![deep]), "all: true"); + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + exit(&mut s, json!({"all": false})); + assert_eq!(isolation(&s), Some(mid), "all: false"); + for bad in [json!({"all": 1}), json!({"all": "yes"}), json!({"all": null})] { + let e = s.execute("object.exitIsolation", &bad).unwrap_err().to_string(); + assert!(e.contains("`all` must be true or false"), "{bad}: {e}"); + assert_eq!(isolation(&s), Some(mid), "{bad}: still isolated"); + } + + // A parent layer hidden while its sublayer is isolated isn't isolated: the call leaves. + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + s.execute("layer.setProps", &json!({"id": mid.0, "visible": false})).unwrap(); + exit(&mut s, json!({})); + assert_eq!(isolation(&s), None, "hidden parent layer"); + s.execute("layer.setProps", &json!({"id": mid.0, "visible": true})).unwrap(); + + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![g]), "a group in a sublayer"); +} + /// Undo and Redo bring back a selection without the guides, ruler guides or guide paths, that /// Lock Guides has locked since, so a move after them leaves the guides where they are. #[test] @@ -5689,3 +5920,20 @@ fn crop_image_trim_leaves_a_cmyk_image_alone() { let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap(); assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64(), r["height"].as_u64()), (Some(false), Some(4), Some(2)), "{r}"); } + +/// Lock Guides is not an undo step: it adds none, and undo and redo of the steps before it leave +/// the guides locked. +#[test] +fn lock_guides_is_not_an_undo_step() { + let mut s = session(); + let g = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + sel(&mut s, &[g]); + s.execute("view.guides.make", &json!({})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.guides_locked()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.guides_locked()); +} diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 9e20de0ad1..c6699190b6 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -637,6 +637,69 @@ fn an_edited_profile_starts_the_documents_of_its_category() { let _ = std::fs::remove_dir_all(&dir); } +/// The fill, stroke and weight of `id` in the active document. +fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, Option) { + let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap(); + (n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width)) +} + +#[test] +fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("default-style"); + // The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + let style = s.doc().unwrap().doc.graphic_styles[0].clone(); + let red = style.appearance.stroke_paint(); + assert!(matches!(red, Paint::Solid { .. }), "{red:?}"); + assert_eq!(style.appearance.stroke().map(|st| st.width), Some(0.25), "{style:?}"); + // The Mobile profile is saved as shipped. + s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let green = s.paint.fill.clone(); + + // A document from the Print profile starts with the style's fill, stroke and weight, and its art takes them. + s.execute("file.new", &json!({"profile": "Print", "colorMode": "cmyk"})).unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, red.clone(), 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25))); + // Default Fill and Stroke gives the selection and the defaults that look again, as one undo step. + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25))); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + // Nothing to change: no undo step. + let step = s.doc().unwrap().history.step(); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.step(), step); + // The new art is not linked to the style. + assert!(s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().extras().graphic_style.is_none()); + + // A profile with the shipped style, here converted to CMYK, leaves the fill and stroke the user chose. + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00", "keepModel": true})).unwrap(); + s.execute("file.new", &json!({"profile": "Mobile", "colorMode": "cmyk"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk); + assert_eq!(s.paint.fill, green); + // So does a document without a profile, and Default Fill and Stroke there gives white and 1 pt black. + s.execute("file.new", &json!({})).unwrap(); + assert_eq!(s.paint.fill, green); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn the_profile_follows_the_preset_access_and_reset() { let (mut s, dir) = with_profiles("choice"); @@ -682,6 +745,56 @@ fn the_profile_follows_the_preset_access_and_reset() { let _ = std::fs::remove_dir_all(&dir); } +/// The first run's style of text object `id`. +fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle { + let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).cloned().unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &n.kind else { panic!("not type: {n:?}") }; + t.runs[0].style.clone() +} + +#[test] +fn a_profiles_normal_character_style_is_the_default_font() { + let (mut s, dir) = with_profiles("default-font"); + // The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"}); + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + // New type in a document from the profile takes the font, size and Character Alignment. + s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Serif"})).unwrap(); + assert!(made.get("warning").is_none(), "{made}"); + let st = first_run(&s, &made["id"]); + assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Source Serif 4", "Regular", 9.0)); + assert_eq!(st.char_align, vectorcraft_doc::CharAlign::EmBoxBottom); + // A font, size or Character Alignment given to the command still wins. + let made = s + .execute("text.create", &json!({"x": 20, "y": 80, "text": "Sans", "font": "Source Sans 3", "size": 14, "charAlign": "romanBaseline"})) + .unwrap(); + let st = first_run(&s, &made["id"]); + assert_eq!((st.font_family.as_str(), st.size, st.char_align), ("Source Sans 3", 14.0, vectorcraft_doc::CharAlign::RomanBaseline)); + // A family given alone starts in Regular, not the style's Bold, and without its axis settings. + let attrs = json!({"font_style": "Bold", "fontAxes": {"wght": 700}}); + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap(); + let made = s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Inter", "font": "Inter"})).unwrap(); + let st = first_run(&s, &made["id"]); + assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Inter", "Regular")); + assert!(st.font_axes.is_empty(), "{:?}", st.font_axes); + // A font of the style that isn't available is reported, as one given to the command is. + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"font_family": "No Such Family 7498"}})).unwrap(); + let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Missing"})).unwrap(); + assert!(made["warning"].as_str().is_some_and(|w| w.contains("No Such Family 7498")), "{made}"); + + // A document from a profile left as shipped starts type in the default font and size. + s.execute("file.new", &json!({"profile": "Web"})).unwrap(); + let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Default"})).unwrap(); + let st = first_run(&s, &made["id"]); + let default = vectorcraft_doc::CharStyle::default(); + assert_eq!((st.font_family, st.size), (default.font_family, default.size)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { let (mut s, dir) = with_profiles("errors"); diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index e5483d1889..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 @@ -465,6 +470,117 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_ assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); } +/// A confined request packages no linked file whose native document it can't read to check against +/// its read roots: a PDF that needs a password to open, and a native document that doesn't load, +/// even inside the roots. The package is refused before anything is written, with an error that +/// names no file or folder. A PDF without editing data is copied, and the person's package copies +/// every file. +#[test] +fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() { + let home = Folder::new("package-unreadable-home"); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let out = home.file("out"); + let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)); + let refused = |s: &mut Session, p: Value| { + let e = package(s, p.clone()).expect_err("refused"); + assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}"); + assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}"); + assert!(!std::path::Path::new(&out).exists(), "{p}"); + }; + let mut part = session(); + run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})); + std::fs::create_dir_all(home.0.join("art")).unwrap(); + let native = home.file("art/part.vectorcraft"); + let pdf = home.file("art/part.pdf"); + save(&mut part, &native); + let pdf_of = + |part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap(); + let editable = pdf_of(&mut part, json!({"format": "pdf"})); + let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}})); + assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data"); + let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false})); + let poster = |placed: &str| { + let mut s = session(); + let r = run(&mut s, "file.place", json!({"path": placed, "link": true})); + assert_eq!(r["linked"], true, "{r}"); + save(&mut s, &home.file("poster.vectorcraft")); + s + }; + write(&pdf, &editable); + let mut s = poster(&pdf); + write(&pdf, &locked); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + // A package prepared in the confined request and written on another thread. + let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap(); + let e = + std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused"); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}"); + assert!(!std::path::Path::new(&out).exists()); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A PDF listing the editing file without its data (`EF` renamed, the same length). + let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF"); + let mut detached = editable.clone(); + detached[at..at + 3].copy_from_slice(b"/XF"); + assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved"); + write(&pdf, &detached); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A PDF without editing data. + write(&pdf, &plain); + assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); + std::fs::remove_dir_all(&out).unwrap(); + // A PDF whose attachments are too many to search to their end, with a readable editing file + // listed before the ones left unsearched. + let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data); + assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read"); + write(&pdf, &cut); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A native document that doesn't load, rewritten or copied as it is. + let mut s = poster(&native); + write(&native, b"not a document"); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"folder": out, "relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); +} + +/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree +/// whose second subtree has 70,000 nodes, more than are searched. +fn attachments_cut_short(native: &[u8]) -> Vec { + let name = vectorcraft_pdf::EDITING_FILE; + let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes(); + stream.extend_from_slice(native); + stream.extend_from_slice(b"\nendstream"); + let objects = [ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(), + b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(), + format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(), + format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(), + stream, + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, body) in objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); + for at in &offsets { + out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); + out +} + /// A missing link stored as a path relative to the document names a file inside a confined /// request's read root: the package report and Document Info give its stored path. #[test] diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index 708b602d1f..ca72e66eec 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -430,6 +430,8 @@ fn set_live_shape_refuses_an_unknown_key() { json!({"id": 3, "radius": 5}), json!({"ids": [3], "sides": 6, "polygonAngle": 15, "polygonRadius": 20, "sideLength": null, "makeSidesEqual": true}), json!({"pieStart": 30, "pieEnd": 90, "invertPie": true}), + json!({"pieEnd": 90, "constrainPie": true}), + json!({"ids": [3], "lineLength": 72, "lineAngle": 90}), json!({"items": null}), ] { assert!(check_params(ID, &ok).is_ok(), "{ok}"); diff --git a/crates/engine/src/tests/params_cache.rs b/crates/engine/src/tests/params_cache.rs new file mode 100644 index 0000000000..3fc2d629e7 --- /dev/null +++ b/crates/engine/src/tests/params_cache.rs @@ -0,0 +1,168 @@ +//! The params description of each built-in command is parsed once per process; the answers read +//! from it are those of parsing it where they are used. + +use std::hint::black_box; + +use serde_json::{Value, json}; + +use crate::cmd::params::{PARSES, accepted_keys, check_keys, doc_keys, id_stands_for_ids, read_once, takes_key, uncached}; +use crate::{Session, command_specs}; + +/// Every answer the key functions give about `doc` for command `id`, as text. +fn answers(id: &str, doc: &'static str) -> Vec { + let own = doc_keys(doc).map(|p| p.keys).unwrap_or_default(); + let accepted = accepted_keys(doc); + let mut out = vec![format!("{accepted:?}"), format!("{}", id_stands_for_ids(doc))]; + let near = own.first().map(|k| format!("{k}q")); + for key in own.iter().copied().chain(["ids", "id", "zzz"]).chain(near.as_deref()) { + out.push(format!("{key}: {}", takes_key(doc, key))); + } + let all: serde_json::Map = accepted.iter().flatten().map(|k| (k.to_string(), Value::Null)).collect(); + let mut cases = vec![json!({}), json!({"zzz": 1}), Value::Object(all)]; + cases.extend(near.map(|k| json!({ k: 1 }))); + for params in cases { + out.push(format!("{params}: {:?}", check_keys(id, doc, ¶ms))); + } + out +} + +#[test] +fn every_command_gets_the_answers_of_its_parsed_description() { + for c in command_specs() { + assert_eq!(answers(c.id, c.params), uncached(|| answers(c.id, c.params)), "{}", c.id); + } +} + +#[test] +fn a_built_in_description_is_not_parsed_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let run = |s: &mut Session| { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("object.move", &json!({"ids": [id], "dx": 1})).unwrap(); + s.execute("object.move", &json!({"ids": [id], "dx": -1})).unwrap(); + for c in command_specs() { + black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params))); + black_box(check_keys(c.id, c.params, &json!({"zzz": 1})).is_err()); + } + }; + run(&mut s); + PARSES.set(0); + run(&mut s); + assert_eq!(PARSES.get(), 0, "descriptions parsed again"); + // Without the table each command parses its description where it is used. + uncached(|| run(&mut s)); + assert!(PARSES.get() > command_specs().len()); +} + +/// A description that isn't a built-in command's, even with the same words (a plug-in's), is parsed +/// where it is used, and so is one that names a plug-in command, whose keys change as plug-ins are +/// installed and removed. +#[test] +fn other_descriptions_are_parsed_where_they_are_used() { + let spec = command_specs().iter().find(|c| id_stands_for_ids(c.params)).unwrap(); + let copy: &'static str = String::from(spec.params).leak(); + assert_eq!(answers(spec.id, copy), answers(spec.id, spec.params)); + PARSES.set(0); + assert!(takes_key(copy, "ids") && id_stands_for_ids(copy)); + assert!(PARSES.get() > 0); + assert!(read_once("{a, …settings as file.new}")); + assert!(!read_once("{a, …settings as plugin.some.command}")); + assert!(!read_once("{a, …the options of `plugin.some.command`}")); +} + +/// This thread's CPU time in ns where Linux reports it, else the time since `start`. +fn now(start: std::time::Instant) -> (u128, bool) { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse().ok()); + match cpu { + Some(ns) => (ns, true), + None => (start.elapsed().as_nanos(), false), + } +} + +fn median(mut v: Vec) -> u128 { + v.sort_unstable(); + v[v.len() / 2] +} + +/// `cargo test --release -p vectorcraft-engine --lib params_cache -- --ignored --nocapture` prints +/// the time of the key questions over every built-in description and of `Session::execute` on a +/// one-object document, with descriptions parsed where they are used (`parse`) and read once +/// (`once`), alternating in one process: the median of 7 runs, in this thread's CPU time on Linux. +#[test] +#[ignore = "benchmark"] +fn bench_params_keys_once() { + let start = std::time::Instant::now(); + let specs = command_specs(); + let questions = || { + for c in specs { + black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"))); + black_box((takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params))); + } + }; + let time = |f: &dyn Fn()| { + let t = now(start); + f(); + (now(start).0 - t.0, t.1) + }; + questions(); + uncached(questions); + let (mut parse, mut once, mut cpu) = (Vec::new(), Vec::new(), true); + for _ in 0..7 { + let (p, c1) = time(&|| uncached(|| (0..200).for_each(|_| questions()))); + let (o, c2) = time(&|| (0..200).for_each(|_| questions())); + parse.push(p); + once.push(o); + cpu &= c1 && c2; + } + let per = |ns: u128| ns / (200 * specs.len() as u128); + println!("clock: {}", if cpu { "thread CPU time" } else { "wall time" }); + println!("key questions, ns per description: parse {} once {}", per(median(parse)), per(median(once))); + for (cmd, params) in [("select.set", "ids"), ("object.move", "move")] { + let doc = || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let p = if params == "ids" { json!({"ids": [id]}) } else { json!({"ids": [id], "dx": 1}) }; + (s, p) + }; + let run = |s: &mut Session, p: &Value| { + for _ in 0..20_000 { + black_box(s.execute(cmd, p).unwrap()); + } + }; + let ((mut a, pa), (mut b, pb)) = (doc(), doc()); + assert_eq!(uncached(|| a.execute(cmd, &pa).unwrap()), b.execute(cmd, &pb).unwrap(), "{cmd}: both ways give the same result"); + let timed = |s: &mut Session, p: &Value, cached: bool| { + let t = now(start).0; + if cached { + run(s, p) + } else { + uncached(|| run(s, p)) + } + now(start).0 - t + }; + let (mut parse, mut once) = (Vec::new(), Vec::new()); + for i in 0..7 { + let (mut s1, p1) = doc(); + let (mut s2, p2) = doc(); + if i % 2 == 0 { + parse.push(timed(&mut s1, &p1, false)); + once.push(timed(&mut s2, &p2, true)); + } else { + once.push(timed(&mut s2, &p2, true)); + parse.push(timed(&mut s1, &p1, false)); + } + // Each document has a `uid` of its own. + let state = |s: &Session| { + let mut d = crate::inspect::document(s); + d.as_object_mut().unwrap().remove("uid"); + d + }; + assert_eq!(state(&s1), state(&s2), "{cmd}: same document"); + } + let ms = |ns: u128| ns as f64 / 1e6; + println!("{cmd} x 20,000: parse {:.1} ms once {:.1} ms", ms(median(parse)), ms(median(once))); + } +} 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/perspgrid.rs b/crates/engine/src/tests/perspgrid.rs index 4b7c1c2ae4..b4f8d89ca3 100644 --- a/crates/engine/src/tests/perspgrid.rs +++ b/crates/engine/src/tests/perspgrid.rs @@ -312,6 +312,91 @@ fn view_options_toggle_without_undo_steps_and_survive_presets() { assert_eq!(PerspectiveGrid::from_doc(&back), Some(g)); } +/// The view options are not undo steps, so undo and redo of other steps leave them as they are: +/// Lock Grid, Lock Station Point, Snap to Grid, Show Rulers and whether the grid shows. Undoing a +/// grid definition brings back the old grid with the current view options. +#[test] +fn undo_and_redo_keep_the_view_options() { + let mut s = session(); + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + let old = grid(&s); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})); + run(&mut s, "perspective.grid.preset", json!({"kind": 1})); + let n = undo_len(&s); + for (id, on) in + [("perspective.grid.lock", true), ("perspective.grid.lockStation", true), ("perspective.grid.snap", false), ("perspective.grid.rulers", true)] + { + run(&mut s, id, json!({"on": on})); + } + run(&mut s, "perspective.grid.show", json!({"visible": false})); + assert_eq!(undo_len(&s), n); + let view = |g: &PerspectiveGrid| (g.locked, g.lock_station, g.snap, g.rulers, g.visible); + let want = (true, true, false, true, false); + assert_eq!(view(&grid(&s)), want); + // Undo the one-point preset: the two-point grid comes back with today's view options. + s.execute("edit.undo", &json!({})).unwrap(); + let g = grid(&s); + assert_eq!((g.kind, g.vp_left, view(&g)), (old.kind, old.vp_left, want)); + // Undo the rectangle, which left the grid alone. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); + // An option changed now holds through the redo steps. + run(&mut s, "perspective.grid.lock", json!({"on": false})); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let g = grid(&s); + assert_eq!((g.kind, view(&g)), (1, (false, true, false, true, false))); +} + +/// The view options set on a document whose steps hold no grid yet stay as they are when undo +/// brings back a step without one, and the active plane chosen without an undo step stays too. +#[test] +fn undo_keeps_the_view_options_of_a_grid_no_step_defined() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})); + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 40})); + assert!(!s.doc().unwrap().doc.unknown.contains_key(vectorcraft_tools::distort::perspective::DOC_KEY)); + run(&mut s, "perspective.grid.show", json!({"visible": true})); + run(&mut s, "perspective.grid.lock", json!({"on": true})); + run(&mut s, "perspective.grid.snap", json!({"on": false})); + run(&mut s, "perspective.plane.set", json!({"plane": "ground"})); + let view = |g: &PerspectiveGrid| (g.visible, g.locked, g.snap, g.plane); + let want = (true, true, false, vectorcraft_tools::distort::perspective::Plane::Ground); + assert_eq!(view(&grid(&s)), want); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); +} + +/// A step that changed a view option itself takes it back on undo and sets it again on redo: a +/// preset shows the grid, and a grid definition can lock it. +#[test] +fn undo_takes_back_the_view_options_a_step_changed() { + let mut s = session(); + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + run(&mut s, "perspective.grid.show", json!({"visible": false})); + run(&mut s, "perspective.grid.preset", json!({"kind": 1})); + assert!(grid(&s).visible); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!grid(&s).visible, "the preset showed the grid"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(grid(&s).visible); + let cell = grid(&s).cell; + run(&mut s, "perspective.grid.set", json!({"locked": true, "cell": cell + 10.0})); + assert!(grid(&s).locked); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).cell), (false, cell)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).cell), (true, cell + 10.0)); + // An option the step left alone and changed after it stays as it is. + run(&mut s, "perspective.grid.snap", json!({"on": false})); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).snap), (false, false)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).snap), (true, false)); +} + /// Lock Grid, Lock Station Point, Snap to Grid and Show Rulers refuse an `on` given as text or as /// another value that is not true or false: the grid and the undo history stay as they were. Null is /// read as the key left out, so it toggles the option. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 8ea5d9f3b5..947a3ec42d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4446,6 +4446,59 @@ fn a_cancelled_filter_run_changes_nothing() { assert_eq!(s.doc().unwrap().doc, before); } +/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter +/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as +/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's +/// larger budget stay as they are, and setting Normal again applies to the next run. +#[test] +fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() { + use cmd::plugin::FilterRun; + let mut s = session(); + let id = "test.engine.largebudget"; + let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string(); + // More steps than a light budget pays for, fewer than 5 times it. + install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output)); + let p = json!({"id": id, "ids": []}); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo)); + + run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"})); + let light = vectorcraft_plugins::Limits::default(); + let large = FilterRun::prepare(&s, &p).unwrap().limits().clone(); + assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() }); + assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms)); + // Cancel still stops it, and it changes nothing. + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p)); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo)); + let made = run(&mut s, "plugin.run", p.clone())["ids"].clone(); + assert_eq!(made.as_array().map(Vec::len), Some(1)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + + // A heavy filter keeps its larger budget with either choice. + let heavy_id = "test.engine.largebudget.heavy"; + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true})); + let hp = json!({"id": heavy_id, "ids": []}); + for budget in ["large", "normal"] { + run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget})); + let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone(); + let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS); + assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}"); + } + + // Normal again: the next run runs out of instructions. + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + run(&mut s, "plugin.remove", json!({"id": id})); + run(&mut s, "plugin.remove", json!({"id": heavy_id})); +} + /// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list). fn with_commands(id: &str, kind: &str, commands: &str) -> String { format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#) @@ -4511,9 +4564,10 @@ fn plugin_commands_are_registered_run_and_removed() { install_wat(&mut s, &tpl::module(&tpl::manifest(id, "filter", "{}"), tpl::ECHO, "", 1)); assert!(listed(&s, grow).is_none() && crate::cmd::find_command(grow).is_none()); install_wat(&mut s, &grower(id)); - assert!(listed(&s, grow).is_some()); + assert!(listed(&s, grow).is_some() && crate::cmd::find_command(grow).is_some()); run(&mut s, "plugin.remove", json!({"id": id})); assert!(listed(&s, grow).is_none() && listed(&s, tidy).is_none()); + assert!(crate::cmd::find_command(grow).is_none() && crate::cmd::find_command(tidy).is_none()); assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs"); } diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 81cea5fd59..966e68dc60 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -109,6 +109,23 @@ fn grid_prefs_apply_to_open_documents() { assert_eq!((g.spacing, g.subdivisions), (36.0, 4)); } +/// The grid preferences are not an undo step in the documents they apply to, so undo and redo +/// leave the grid as the preferences set it. +#[test] +fn undo_and_redo_keep_the_grid_prefs() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + s.execute("prefs.set", &json!({"values": {"gridlineEvery": 36, "gridSubdivisions": 4}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let g = &s.doc().unwrap().doc.grid; + assert_eq!((g.spacing, g.subdivisions), (36.0, 4)); + s.execute("prefs.set", &json!({"values": {"gridlineEvery": 18, "gridSubdivisions": 3}})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let g = &s.doc().unwrap().doc.grid; + assert_eq!((g.spacing, g.subdivisions), (18.0, 3)); +} + /// Guides & Grid › Gridline every and Subdivisions (#394): set with no document open, as the /// desktop app restores them at launch, they give `file.new`'s document their grid. #[test] @@ -447,6 +464,38 @@ fn gpu_preference_defaults_to_automatic_and_validates() { assert_eq!(s.prefs.gpu_preference, "automatic"); } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or +/// label, kept through a save and load, and reset with its category. Setting another value is an +/// error that changes nothing; a saved value that is missing, unknown or of another type reads as +/// Normal and leaves the other saved preferences as they are. +#[test] +fn plugin_instruction_budget_defaults_to_normal_and_validates() { + let mut s = Session::new(); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal); + assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal")); + set_pref(&mut s, "pluginInstructionBudget", json!("Large")); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large); + assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large")); + for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] { + assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}"); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}"); + } + let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(back.plugin_instruction_budget, PluginBudget::Large); + let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")]; + let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v})); + for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) { + let read: Prefs = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}"); + } + let l = s.execute("prefs.list", &json!({})).unwrap(); + let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone(); + assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins"))); + assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large"))); + s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap(); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal); +} + /// Performance › Low-Latency Drawing (#6013): off by default and for preference files written /// before it, a boolean only, kept through a save/load round trip, listed under Performance and /// reset with it. 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/tests/styles.rs b/crates/engine/src/tests/styles.rs index 6f0242c662..dd5ca1d9f8 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() { assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance)); } +/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id, +/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as +/// they are, in one undo step. A style replaced by itself or by a style with the same look records +/// nothing, and bad parameters are errors that change nothing. +#[test] +fn redefine_from_a_style_gives_the_style_that_look() { + let mut s = session(); + let (a, b, c) = linked_three(&mut s); + let d = rect(&mut s, 300.0); + set_fill(&mut s, d, "#0000ff"); + run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"})); + run(&mut s, "graphicStyle.new", json!({"name": "Blue"})); + set_fill(&mut s, c, "#00ff00"); + let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s)); + assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S"); + assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() }); + assert_eq!(names(&s), order); + let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap()); + for id in [a, b] { + let n = node(&s, id); + assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply)); + } + assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]); + // The edited object keeps its look and is unlinked; Blue and its object are as they were. + assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap())); + assert_eq!(node(&s, c).extras().graphic_style, None); + assert_eq!(style(&s, "Blue"), blue); + assert_eq!(linked(&mut s, "Blue"), vec![d.0]); + let step = s.doc().unwrap().history.undo.last().unwrap().clone(); + assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(style(&s, "S"), old); + assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE))); + assert_eq!(node(&s, c).extras().graphic_style, Some(old.id)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(style(&s, "S").appearance, blue.appearance); + assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]); + run(&mut s, "edit.undo", json!({})); + + // A style replaced by itself, or by a copy with the same look, records nothing. + run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"})); + let before = steps(&s); + run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"})); + run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"})); + assert_eq!(steps(&s), before); + assert_eq!(style(&s, "S"), old); + + // A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors. + for p in [ + json!({"name": "S", "from": "nope"}), + json!({"name": "nope", "from": "Blue"}), + json!({"name": "S", "from": 3}), + json!({"name": "S", "from": "Blue", "id": a.0}), + json!({"from": "Blue"}), + ] { + assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}"); + } + assert_eq!((steps(&s), style(&s, "S")), (before, old)); +} + #[test] fn deleting_a_style_unlinks_and_renaming_keeps_links() { let mut s = session(); diff --git a/crates/engine/src/tests/symboledit.rs b/crates/engine/src/tests/symboledit.rs index 450572b731..47dfeacc5e 100644 --- a/crates/engine/src/tests/symboledit.rs +++ b/crates/engine/src/tests/symboledit.rs @@ -253,6 +253,28 @@ fn redefining_the_symbol_being_edited_leaves_symbol_editing_mode_in_the_same_ste assert!(st.doc.symbol_edit.is_some()); } +/// Redefining the symbol being edited with `keepArt: true` also leaves symbol editing mode in the +/// same step; the art outside the editing layer stays ordinary art and stays selected, and the +/// art on the editing layer still can't redefine it. +#[test] +fn redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode() { + let (mut s, first, second) = two_instances(); + let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 30, "height": 30}))); + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap()); + let e = s.execute("symbol.update", &json!({"name": "Box", "keepArt": true})).unwrap_err().to_string(); + assert!(e.contains("can't hold an instance of itself"), "{e}"); + let steps = s.doc().unwrap().history.undo.len(); + let r = run(&mut s, "symbol.update", json!({"name": "Box", "ids": [other.0], "keepArt": true})); + assert!(r["id"].is_null(), "{r}"); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none()); + assert_eq!(st.history.undo.len(), steps + 1); + assert!(matches!(st.doc.node(other).map(|n| &n.kind), Some(NodeKind::Path { .. })), "the art stays ordinary art"); + assert_eq!(st.selection.objects, vec![other], "the art stays selected"); + assert!(is_instance(&s, first), "the instance editing was entered from is still an instance"); + assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second)); +} + #[test] fn leaving_goes_back_to_the_isolation_before_and_undo_keeps_a_group_isolated_inside() { let (mut s, first, _) = two_instances(); diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index c5d32e822a..02e45a7153 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -375,3 +375,69 @@ fn other_documents_symbols_load_and_unreadable_files_are_errors() { let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); assert_eq!(vectorcraft_format::load(&bytes).unwrap().symbols.len(), 1); } + +/// `symbol.placeFromDocument` places another open document's symbol in the active document as +/// one undo step, with the symbol it nests, the pattern its art uses and its Symbol Options. A +/// second placement uses what the first added; the source document is left as it was; a symbol +/// of the active document itself is placed as it is; a closed document, a name the document does +/// not have and bad params are errors that change nothing. +#[test] +fn another_documents_symbol_is_added_and_placed_in_one_step() { + let mut s = kit(); + let source = s.doc().unwrap().uid; + let source_doc = s.doc().unwrap().doc.clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let before = undo_len(&s); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40})); + assert_eq!(undo_len(&s), before + 1, "added and placed in one step"); + assert_eq!(r["name"], "Badge"); + let mut names = symbols(&s); + names.sort(); + assert_eq!(names, ["Badge", "Star"], "the nested Star came along"); + assert_eq!(doc(&s).symbol_registration("Badge"), SymbolRegistration(0)); + let placed = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().selection.objects, [placed]); + let NodeKind::SymbolInstance { symbol, .. } = &doc(&s).node(placed).unwrap().kind else { panic!("not an instance") }; + assert_eq!(symbol, "Badge"); + let size = |d: &vectorcraft_doc::Document| d.unknown.get("symbolSizes").and_then(|m| m.get("Badge")).cloned(); + assert!(size(doc(&s)).is_some()); + assert_eq!(size(doc(&s)), size(&source_doc)); + // The Dots symbol brings its pattern and swatch. + run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Dots"})); + assert!(doc(&s).pattern("Dots").is_some() && doc(&s).swatch("Dots").is_some()); + // Placed again, Badge is the one already added. + let count = doc(&s).symbols.len(); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge"})); + assert_eq!((r["name"].as_str(), doc(&s).symbols.len()), (Some("Badge"), count)); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(symbols(&s).is_empty() && doc(&s).pattern("Dots").is_none()); + // The active document's own symbol, by its uid: placed, nothing added. + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + run(&mut s, "symbol.new", json!({"name": "Star"})); + let own = s.doc().unwrap().uid; + let before = undo_len(&s); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": own, "name": "Star", "x": 70, "y": 70})); + assert_eq!((undo_len(&s), r["name"].as_str(), symbols(&s)), (before + 1, Some("Star"), vec!["Star".to_string()])); + // Errors change nothing. + let before = (undo_len(&s), doc(&s).clone()); + for p in [ + json!({"sourceDocument": source, "name": "Nope"}), + json!({"sourceDocument": source}), + json!({"name": "Star"}), + json!({"sourceDocument": -1, "name": "Star"}), + json!({"sourceDocument": "1", "name": "Star"}), + json!({"sourceDocument": source, "name": "Star", "x": "10"}), + json!({"sourceDocument": u64::MAX, "name": "Star"}), + ] { + assert!(s.execute("symbol.placeFromDocument", &p).is_err(), "{p}"); + assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{p}"); + } + // The source document is left as it was, and once it is closed its symbols are gone with it. + assert!(s.set_active(0)); + assert_eq!(*s.doc().unwrap().doc, *source_doc); + run(&mut s, "file.close", json!({"index": 0})); + let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err(); + assert!(e.to_string().contains("no longer open"), "{e}"); +} diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index cc89a8261b..980682f57e 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -135,6 +135,36 @@ fn text_files_report_and_queue_with_their_options() { assert!(close(frame, Rect::new(50.0, 60.0, 130.0, 100.0)), "{frame:?}"); } +/// Text Import Options' other character sets place their text as area type, and an unknown +/// character set is refused with the list of sets and places nothing. +#[test] +fn text_files_place_in_the_other_character_sets() { + let mut s = session(); + let cases: [(&str, &str, &[u8], &str); 11] = [ + ("shiftJis", "windows", &[0x93, 0xFA, 0x96, 0x7B], "日本"), + ("gb2312", "windows", &[0xD6, 0xD0, 0xCE, 0xC4], "中文"), + ("chineseBig5", "mac", &[0xA4, 0xA4, 0xA4, 0xE5], "中文"), + ("cyrillic", "windows", &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + ("cyrillic", "mac", &[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + ("gb18030", "windows", &[0x95, 0x32, 0x82, 0x36], "\u{20000}"), + ("greek", "windows", &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"), + ("turkish", "mac", &[0xDD, 0x73, 0x74], "İst"), + ("baltic", "windows", &[0x52, 0xEE, 0x67, 0x61], "Rīga"), + ("centralEuropean", "windows", &[0xA3, 0xF3, 0x64, 0x9F, b'\r', b'\n', 0xA3], "Łódź\nŁ"), + ("shiftJis", "windows", &[0x82, 0x22], "\u{FFFD}\""), + ]; + for (set, platform, bytes, text) in cases { + let r = place_text(&mut s, bytes, json!({"text": {"characterSet": set, "platform": platform}})); + assert_eq!(placed(&s, &r).0, text, "{set} on {platform}"); + } + let undo = s.doc().unwrap().history.undo.len(); + let bad = json!({"name": "a.txt", "dataBase64": "YQ==", "text": {"characterSet": "latin9"}}); + let err = s.execute("file.place", &bad).unwrap_err().to_string(); + let list = r#""unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#; + assert!(err.contains(&format!("text.characterSet `latin9`: use {list}")), "{err}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing placed"); +} + /// An RTF file with a font table, a color table, a bold run, an italic run, a superscript and a /// centered, indented second paragraph. const LETTER_RTF: &str = concat!( diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index a9d9e3f5bd..fbde9edca7 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -246,7 +246,12 @@ fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() { let mut s = session(); for active in [false, true] { select(&mut s, if active { "spiral" } else { "selection" }); - let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap(); + // A decay past the 99.99 % a spiral draws is refused, and nothing changes. + let before = s.tool_options_of("spiral"); + let refused = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})); + assert_eq!(refused.err(), Some("tool `spiral`: `decay` must be a number from 5 to 99.99".to_string())); + assert_eq!(s.tool_options_of("spiral"), before); + let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 99.99, "segments": 4, "clockwise": false}})).unwrap(); assert_eq!(options["decay"], json!(99.99)); assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99)); assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99)); @@ -387,3 +392,110 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() { assert_eq!(s.tool_options()["fidelity"], json!(3.0), "{id}"); } } + +/// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an +/// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also +/// when another option given with it is good, and nothing is saved or recorded for undo. +#[test] +fn bad_option_values_are_errors_that_set_nothing() { + let mut s = session(); + select(&mut s, "smooth"); + let (options, saved, undo) = (s.tool_options(), s.prefs.tool_settings.clone(), s.doc().unwrap().history.undo.len()); + let fidelity = "tool `smooth`: `fidelity` must be a number from 0.05 to 100"; + for bad in [json!("abc"), json!(true), json!(-3), json!(1e9), json!(null), json!([2])] { + assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": bad})).unwrap_err(), fidelity, "{bad}"); + } + let cases = [ + (json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"), + (json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"), + (json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"), + (json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"), + (json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"), + (json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"), + ( + json!({"tool": "mirrorCut", "key": "axis", "value": "diagonal"}), + "tool `mirrorCut`: `axis` must be one of `vertical`, `horizontal`, `free`", + ), + (json!({"tool": "selection", "key": "fidelity", "value": 4}), "tool `selection`: unknown option `fidelity`"), + (json!({"values": [1]}), "`values` must be an object"), + (json!({"tool": 3, "key": "fidelity", "value": 4}), "`tool` must be a tool id"), + (json!({"key": "fidelity"}), "`value` is missing for `fidelity`"), + ]; + for (p, want) in cases { + assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); + } + assert_eq!(s.tool_options_of("pencil")["closeWithin"], session().tool_options_of("pencil")["closeWithin"]); + assert_eq!((s.tool_options(), &s.prefs.tool_settings, s.doc().unwrap().history.undo.len()), (options, &saved, undo)); + // A good value after the errors is set and read back. + assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": 9})).unwrap()["fidelity"], json!(9.0)); +} + +/// `tool.setOption {}` reads the options, of the active tool or of the tool named, and saves nothing. +#[test] +fn an_empty_set_option_reads_and_saves_nothing() { + let mut s = session(); + select(&mut s, "smooth"); + let saved = s.prefs.tool_settings.clone(); + assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options()); + assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare")); + // No params (null) read too; params that are not an object are an error. + assert_eq!(s.set_tool_option_cmd(&serde_json::Value::Null).unwrap(), s.tool_options()); + for (bad, got) in [(json!(true), "true"), (json!([]), "[]")] { + assert_eq!(s.set_tool_option_cmd(&bad).unwrap_err(), format!("the params must be an object, not {got}")); + } + assert_eq!(s.prefs.tool_settings, saved); +} + +/// A Place queue with a malformed entry is an error, and the queue held stays as it was. +#[test] +fn a_malformed_place_queue_is_an_error() { + let mut s = session(); + select(&mut s, "place"); + let entry = json!({"params": {"svg": ""}, "name": "a", "width": 10, "height": 10}); + s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry]}})).unwrap(); + let bad = json!({"params": {}, "name": "b", "width": "wide", "height": 10}); + let e = s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry, bad]}})).unwrap_err(); + assert!(e.starts_with("tool `place`: `queue` must be"), "{e}"); + assert_eq!(s.tool_options()["names"], json!(["a"])); + assert_eq!( + s.set_tool_option_cmd(&json!({"key": "current", "value": 1})).unwrap_err(), + "tool `place`: `current` must be the index of a queued file, from 0 to 0" + ); +} + +/// A `current` given with a new Place queue picks among the files of that queue. +#[test] +fn a_place_queue_and_its_current_file_set_together() { + let mut s = session(); + select(&mut s, "place"); + let entry = |name: &str| json!({"params": {"svg": ""}, "name": name, "width": 10, "height": 10}); + let queue = json!({"entries": [entry("a"), entry("b"), entry("c")]}); + let out = s.set_tool_option_cmd(&json!({"values": {"queue": queue, "current": 2}})).unwrap(); + assert_eq!((out["names"].clone(), out["current"].clone()), (json!(["a", "b", "c"]), json!(2))); + let short = json!({"entries": [entry("d")]}); + let e = s.set_tool_option_cmd(&json!({"values": {"queue": short, "current": 2}})).unwrap_err(); + assert_eq!(e, "tool `place`: `current` must be the index of a queued file, from 0 to 0"); + assert_eq!(s.tool_options()["names"], json!(["a", "b", "c"]), "a refused call keeps the queue held"); +} + +/// A value given with a parametric shape's new `kind` is checked against that kind's range and +/// set on it, whether the tool is chosen or not. +#[test] +fn a_parametric_shape_kind_and_its_values_set_together() { + for active in [false, true] { + let mut s = session(); + if active { + select(&mut s, "parametricShape"); + } + let set = |s: &mut Session, values: serde_json::Value| s.set_tool_option_cmd(&json!({"tool": "parametricShape", "values": values})); + set(&mut s, json!({"kind": "polygon"})).unwrap(); + let out = set(&mut s, json!({"kind": "star", "a": 0.8})).unwrap(); + assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(0.8)), "active {active}"); + set(&mut s, json!({"kind": "ring"})).unwrap(); + let out = set(&mut s, json!({"kind": "star", "a": 1.0})).unwrap(); + assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(1.0)), "active {active}"); + let e = set(&mut s, json!({"kind": "ring", "a": 1.0})).unwrap_err(); + assert!(e.contains("`a`"), "{e}"); + assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing"); + } +} diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index a731e51aca..fe3deecbef 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -453,6 +453,282 @@ fn colour_table_lock_web_shift_snap_and_sort() { assert!(lossy < plain, "{lossy} vs {plain}"); } +/// Delete Color: the deleted colors leave the table and the file, their pixels take the nearest +/// color left, and the edit stays with the settings until another reduction is chosen. +#[test] +fn colour_table_delete_maps_pixels_to_the_nearest_color_left() { + // 40×10: red, a near red and blue, and 10 px with nothing (transparent). + let mut s = session(40.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p); + let sources = |v: &Value| -> Vec { + let mut out: Vec = + v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| c["source"].as_str().unwrap().to_string()).collect(); + out.sort(); + out + }; + let base = preview(&mut s, json!({"dither": "none"})); + assert_eq!(base["colors"].as_array().unwrap().len(), 4, "{base}"); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "colorTable": {"deleted": ["#EE1100"]}}); + let v = preview(&mut s, p.clone()); + assert_eq!(v["colors"].as_array().unwrap().len(), 3, "{format}: {v}"); + assert!(v["colors"].as_array().unwrap().iter().any(|c| c["transparent"] == true), "{format}: the transparent entry stays"); + assert_eq!(sources(&v), ["#0000ff", "#ff0000"], "{format}"); + let file = one(&mut s, p); + assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file"); + let img = pixels(&file); + assert_eq!(img.get_pixel(15, 5).0, [255, 0, 0, 255], "{format}: the nearest color left"); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), ([255, 0, 0, 255], [0, 0, 255, 255], 0)); + assert_eq!(distinct(&img), 3, "{format}"); + } + // A color the table does not hold is no edit; sorting does not bring a deleted one back. + assert_eq!(sources(&preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#123456"]}}))).len(), 3); + let sorted = preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#ee1100"], "sort": "luminance"}})); + assert_eq!(sources(&sorted), ["#0000ff", "#ff0000"]); + // A fixed palette: colors it lacks are not made again, and deletions come out of it. + let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}})); + assert_eq!(sources(&fixed), ["#0000ff", "#ff0000"]); + let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"], "deleted": ["#ff0000"]}})); + assert_eq!(sources(&fixed), ["#0000ff"]); + // At most `colors` entries of a fixed palette, the transparent one included. + let two = preview(&mut s, json!({"dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}})); + assert_eq!(sources(&two), ["#0000ff"]); + // Deleting every opaque color is refused: the pixels need a color. + // Colors mapped to transparent do not count as left. + for table in [ + json!({"deleted": ["#ff0000", "#ee1100", "#0000ff"]}), + json!({"customPalette": ["#ff0000"], "deleted": ["#ff0000"]}), + json!({"deleted": ["#0000ff", "#ee1100"], "transparent": ["#ff0000"]}), + json!({"customPalette": ["#ff0000", "#0000ff"], "deleted": ["#0000ff"], "transparent": ["#ff0000"]}), + ] { + let p = json!({"colorTable": table}); + let e = s.execute("document.exportForWeb.preview", &p).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains(cmd::webexport::KEEP_ONE), "{p}: {e}"); + assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}"); + } + for bad in [ + json!({"colorTable": {"deleted": ["nope"]}}), + json!({"colorTable": {"customPalette": ["#ff000080"]}}), + json!({"colorTable": {"deleted": vec!["#ff0000"; 257]}}), + ] { + assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}"); + assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}"); + } + // A deleted color leaves the other lists; JPEG and PNG-24 have no table to edit. + let table = json!({ + "deleted": ["#ee1100"], "customPalette": ["#ff0000", "#ee1100", "#0000ff"], "locked": ["#EE1100", "#0000ff"], + "transparent": ["#ee1100"], "webShift": ["#ee1100"], + }); + let r = run(&mut s, "webExport.settings", json!({ "colorTable": table })); + let t = r["settings"]["colorTable"].clone(); + assert_eq!((&t["locked"], &t["transparent"], &t["webShift"]), (&json!(["#0000ff"]), &json!([]), &json!([]))); + assert_eq!(t["deleted"], json!(["#ee1100"])); + for format in ["jpg", "png24"] { + assert!(preview(&mut s, json!({"format": format, "colorTable": t.clone()})).get("colors").is_none(), "{format}"); + } + // The remembered edit survives other keys and a format change, and goes with another reduction. + let r = run(&mut s, "webExport.settings", json!({"colors": 64, "format": "png8"})); + assert_eq!(r["settings"]["colorTable"]["deleted"], json!(["#ee1100"])); + let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"})); + assert_eq!((&r["settings"]["colorTable"]["deleted"], &r["settings"]["colorTable"]["customPalette"]), (&json!([]), &json!([]))); + // A saved preset keeps the edit. + run(&mut s, "webExport.presets.save", json!({"name": "No near red", "dither": "none", "colorTable": {"deleted": ["#ee1100"]}})); + assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]); +} + +/// The colors of a fixed palette mapped to transparent take one slot of Colors together with the +/// transparent pixels, so the opaque colors after them still fit: their pixels stay opaque, and the +/// pixels of the colors mapped to transparent become transparent. +#[test] +fn colour_table_fixed_palette_keeps_an_opaque_color() { + // 40×10: red, a near red and blue, and 10 px with nothing (transparent). + let mut s = session(40.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + for table in [ + json!({"customPalette": ["#ff0000", "#ee1100", "#0000ff"], "deleted": ["#ee1100"], "transparent": ["#ff0000"]}), + json!({"customPalette": ["#ff0000", "#0000ff"], "transparent": ["#ff0000"]}), + ] { + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table}); + let v = run(&mut s, "document.exportForWeb.preview", p.clone()); + let opaque: Vec<&Value> = v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| &c["source"]).collect(); + assert_eq!((opaque, v["colors"].as_array().unwrap().len()), (vec![&json!("#0000ff")], 2), "{p}"); + let img = pixels(&one(&mut s, p.clone())); + let alpha = |x: u32| img.get_pixel(x, 5).0[3]; + assert_eq!((alpha(5), alpha(15), img.get_pixel(25, 5).0, alpha(35)), (0, 0, [0, 0, 255, 255], 0), "{p}"); + } + // A color mapped to transparent that no pixel takes leaves its slot to an opaque color. + let mut u = session(20.0, 10.0); + rect(&mut u, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut u, [10.0, 0.0, 10.0, 10.0], "#00ff00"); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#00ff00", "#ff0000"], "transparent": ["#ff0000"]}}); + let img = pixels(&one(&mut u, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0), ([0, 0, 255, 255], [0, 255, 0, 255])); + // At 256 colors a color mapped to transparent after 255 opaque ones still keeps an entry. + let full: Vec = + std::iter::once("#0000ff".to_string()).chain((1..255).map(|i| format!("#00{i:02x}00"))).chain(["#ff0000".to_string()]).collect(); + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}}); + let img = pixels(&one(&mut s, p)); + assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0)); + // With one opaque color and 255 mapped to transparent, the last of those does not fit, and its + // pixels still become transparent rather than taking the opaque color nearest them. + let mut d = session(30.0, 10.0); + rect(&mut d, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut d, [10.0, 0.0, 10.0, 10.0], "#0000ee"); + let clear: Vec = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect(); + let palette: Vec = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect(); + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}}); + let img = pixels(&one(&mut d, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0)); + // Without transparent pixels the colors mapped to transparent still take one slot together. + let mut t = session(30.0, 10.0); + rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut t, [10.0, 0.0, 10.0, 10.0], "#ee1100"); + rect(&mut t, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": { + "customPalette": ["#ff0000", "#ee1100", "#0000ff", "#00ff00"], "transparent": ["#ff0000", "#ee1100"], + }}); + let v = run(&mut t, "document.exportForWeb.preview", p.clone()); + assert_eq!(v["colors"].as_array().unwrap().len(), 2, "{v}"); + let img = pixels(&one(&mut t, p)); + assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255])); +} + +/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in +/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is +/// the file. +#[test] +fn colour_table_shift_writes_the_picked_color_wherever_the_source_is() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#00ff00"); + let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p); + let entry = |v: &Value, source: &str| v["colors"].as_array().unwrap().iter().find(|c| c["source"] == source).cloned().unwrap_or(Value::Null); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "colorTable": {"shifted": {"#0000FF": "#FF8800"}}}); + let v = preview(&mut s, p.clone()); + let c = entry(&v, "#0000ff"); + assert_eq!( + (c["color"].as_str(), c["shifted"].as_bool(), c["locked"].as_bool(), c["webShifted"].as_bool()), + (Some("#ff8800"), Some(true), Some(true), Some(false)), + "{format}: {v}" + ); + assert_eq!((entry(&v, "#ff0000")["shifted"].as_bool(), entry(&v, "#ff0000")["color"].as_str()), (Some(false), Some("#ff0000"))); + let file = one(&mut s, p); + assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file"); + let img = pixels(&file); + assert_eq!( + (img.get_pixel(5, 5).0, img.get_pixel(12, 2).0, img.get_pixel(18, 8).0, img.get_pixel(25, 5).0), + ([255, 0, 0, 255], [255, 136, 0, 255], [255, 136, 0, 255], [0, 255, 0, 255]), + "{format}" + ); + assert_eq!(distinct(&img), 3, "{format}"); + } + // A shifted color is kept when the colors are reduced, as a locked one is. + let two = preview(&mut s, json!({"colors": 2, "dither": "none", "colorTable": {"shifted": {"#00ff00": "#123456"}}})); + assert_eq!(entry(&two, "#00ff00")["color"], "#123456", "{two}"); + // With one slot to keep, the shifted color takes it before a locked one. + let p = json!({"colors": 2, "dither": "none", "colorTable": {"locked": ["#ff0000"], "shifted": {"#0000ff": "#123456"}}}); + let first = preview(&mut s, p); + assert_eq!(entry(&first, "#0000ff")["color"], "#123456", "{first}"); + // A source the table does not hold shifts nothing, and the shift stays with the settings. + let base = preview(&mut s, json!({"dither": "none"})); + let absent = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#123456": "#000000"}}})); + assert_eq!(absent["colors"], base["colors"]); + // Two colors may be shifted to one color and keep their own sources. + let same = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#ff0000": "#123456", "#0000ff": "#123456"}}})); + assert_eq!((entry(&same, "#ff0000")["color"].as_str(), entry(&same, "#0000ff")["color"].as_str()), (Some("#123456"), Some("#123456"))); + assert_eq!(entry(&same, "#00ff00")["shifted"], false); + // A shift by hand wins over web shift, web snap and a lock; transparency wins over it. + let p = + json!({"dither": "none", "webSnap": 100, "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "webShift": ["#0000ff"], "locked": ["#0000ff"]}}); + let c = entry(&preview(&mut s, p), "#0000ff"); + assert_eq!((c["color"].as_str(), c["webShifted"].as_bool(), c["locked"].as_bool()), (Some("#fe0101"), Some(false), Some(true))); + let clear = json!({"dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "transparent": ["#0000ff"]}}); + let v = preview(&mut s, clear.clone()); + assert!(v["colors"].as_array().unwrap().iter().all(|c| c["shifted"] == false), "{v}"); + assert_eq!(pixels(&one(&mut s, clear)).get_pixel(15, 5).0[3], 0); + // The settings keep the shifts in lowercase, drop a color shifted to itself, a deleted one and + // the web shift of a color shifted by hand. + let table = json!({"shifted": {"#0000FF": "#FE0101", "#FF0000": "#ff0000", "#00ff00": "#000000"}, "webShift": ["#0000ff", "#00ff00"], "deleted": ["#00ff00"]}); + let r = run(&mut s, "webExport.settings", json!({ "colorTable": table })); + let t = &r["settings"]["colorTable"]; + assert_eq!((&t["shifted"], &t["webShift"]), (&json!({"#0000ff": "#fe0101"}), &json!([]))); + // Another reduction keeps the shifts; a saved preset keeps them. + let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"})); + assert_eq!(r["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"})); + run(&mut s, "webExport.presets.save", json!({"name": "Blue to red", "dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}}})); + assert_eq!(entry(&preview(&mut s, json!({"preset": "Blue to red"})), "#0000ff")["color"], "#fe0101"); + // Bad shifts are refused and change nothing. + let many: serde_json::Map = (0..257).map(|i| (format!("#{i:06x}"), json!("#000000"))).collect(); + for bad in [ + json!({"nope": "#000000"}), + json!({"#ff0000": "nope"}), + json!({"#ff0000": "#ff000080"}), + json!({"#ff000080": "#000000"}), + json!({"#ff0000": "#000000", "#FF0000": "#ffffff"}), + json!({"#f00": "#000000", "#ff0000": "#ffffff"}), + Value::Object(many), + ] { + let p = json!({"colorTable": {"shifted": bad}}); + assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}"); + assert!(s.execute("document.exportForWeb.preview", &p).is_err(), "{p}"); + assert!(s.execute("webExport.settings", &p).is_err(), "{p}"); + } + assert_eq!(run(&mut s, "webExport.settings", json!({}))["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"})); + // Settings saved before shifts existed still read. + let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"colorTable": {"locked": ["#ff0000"]}})).unwrap(); + assert!(old.color_table.shifted.is_empty()); +} + +/// Lossy GIF compression leaves the pixels of a color shifted by hand alone, so a color shifted near +/// another one does not take in that color's pixels. +#[test] +fn lossy_does_not_spread_a_shifted_color_into_another() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#c80000"); + let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#be0000"}}}); + let img = pixels(&one(&mut s, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(20, 5).0, img.get_pixel(29, 5).0), ([190, 0, 0, 255], [200, 0, 0, 255], [200, 0, 0, 255])); +} + +/// Lossy GIF compression moves no pixel into or out of a color shifted by hand: the colors next to +/// a shifted one keep their own pixels, and the shifted color keeps all of its pixels. +#[test] +fn lossy_moves_no_pixel_into_or_out_of_a_shifted_color() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1414e6"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#0000ff"); + rect(&mut s, [20.0, 0.0, 30.0, 10.0], "#1414e6"); + let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#ff0000"}}}); + let img = pixels(&one(&mut s, p)); + let near_blue = [20, 20, 230, 255]; + for x in 0..30 { + let want = if (10..20).contains(&x) { [255, 0, 0, 255] } else { near_blue }; + assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}"); + } +} + +/// Lossy GIF compression compares the pixels with the colors web snap writes, so a pixel does not +/// take a color that snaps far from it. +#[test] +fn lossy_compares_pixels_with_the_snapped_colors() { + let mut s = session(20.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1a1a1a"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#000000"); + let img = pixels(&one(&mut s, json!({"format": "gif", "dither": "none", "webSnap": 100, "lossy": 50}))); + for x in 0..20 { + let want = if x < 10 { [51, 51, 51, 255] } else { [0, 0, 0, 255] }; + assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}"); + } +} + #[test] fn presets_and_remembered_settings() { let mut s = two_colours(); diff --git a/crates/engine/src/tests/widthpoints.rs b/crates/engine/src/tests/widthpoints.rs index 6aa324aa90..bed235421e 100644 --- a/crates/engine/src/tests/widthpoints.rs +++ b/crates/engine/src/tests/widthpoints.rs @@ -167,6 +167,124 @@ fn adjust_adjoining_scales_the_neighbours() { assert_eq!(points(&s, id), vec![(0.5, 4.0, 1.0)]); } +/// A line with a discontinuous point in the middle: 1× before it, 2× after it. +fn pair_session(points: serde_json::Value) -> (Session, NodeId) { + let (mut s, id) = line_session(); + s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": points})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + (s, id) +} + +#[test] +fn paired_set_edits_both_halves_in_one_step() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20}); + assert_eq!(set(&mut s, p.clone()), 1); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 2.0, 1.0), (0.5, 3.0, 4.0), (1.0, 1.0, 1.0)]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let after = s.doc().unwrap().doc.clone(); + // The same widths again change nothing and record no undo step. + set(&mut s, p); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after); +} + +#[test] +fn paired_set_adjusts_the_point_before_and_the_point_after_once_each() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + // The incoming half doubles and the outgoing half halves: the start doubles, the end halves. + set( + &mut s, + json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 10, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.5, 2.0, 2.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]); + // A discontinuous point at the start has only a point after it to adjust. + let (mut s, id) = pair_session(json!([[0, 1, 1], [0, 2, 2], [1, 1, 1]])); + set( + &mut s, + json!({"id": id.0, "index": 0, "t": 0, "left": 10, "right": 10, "outIndex": 1, "outLeft": 20, "outRight": 20, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.0, 4.0, 4.0), (1.0, 2.0, 2.0)]); +} + +/// Three points each within 1e-6 of the next: the first two are the pair, and the third, though +/// within 1e-6 of the outgoing half, is the point after the pair that the outgoing half adjusts. +#[test] +fn paired_set_adjusts_the_point_after_a_chained_pair() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.50000075, 2, 2], [0.5000015, 1, 1], [1, 1, 1]])); + set( + &mut s, + json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50000075, 1.0, 1.0), (0.5000015, 0.5, 0.5), (1.0, 1.0, 1.0)]); +} + +#[test] +fn single_width_only_leaves_one_continuous_point() { + for (single, kept) in [("incoming", (2.0, 1.0)), ("outgoing", (3.0, 4.0))] { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20, "single": single}); + assert_eq!(set(&mut s, p), 1); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{single}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + } + // With Adjust Adjoining, each neighbor follows the change of the half beside it. + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "single": "incoming", "adjustAdjoining": true}); + set(&mut s, p); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]); +} + +#[test] +fn paired_set_refuses_what_is_not_one_discontinuous_point() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.25, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [0.75, 3, 3], [0.75, 3, 3], [0.75, 3, 3], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let pair = |extra: serde_json::Value| { + let mut p = json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "outIndex": 3, "outLeft": 5, "outRight": 5}); + for (k, v) in extra.as_object().unwrap() { + if v.is_null() { + p.as_object_mut().unwrap().remove(k); + } else { + p[k] = v.clone(); + } + } + p + }; + for p in [ + pair(json!({"index": 1, "t": 0.25, "outIndex": 2})), + pair(json!({"outIndex": 4})), + pair(json!({"index": 3, "outIndex": 2})), + pair(json!({"outIndex": 99})), + pair(json!({"outIndex": "3"})), + pair(json!({"outIndex": -1})), + pair(json!({"t": 0.6})), + pair(json!({"index": 4, "t": 0.75, "outIndex": 5})), + pair(json!({"index": null})), + pair(json!({"outLeft": null})), + pair(json!({"outRight": -1})), + pair(json!({"outLeft": 1.0e6})), + pair(json!({"single": "both"})), + pair(json!({"single": true})), + pair(json!({"outIndex": null})), + pair(json!({"outIndex": null, "outLeft": null})), + json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "single": "incoming"}), + ] { + assert!(s.execute("stroke.widthPoint.set", &p).is_err(), "accepted {p}"); + assert_eq!(s.doc().unwrap().doc, before, "{p}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + } +} + #[test] fn flipping_along_swaps_the_sides_of_a_discontinuous_point() { let (mut s, id) = line_session(); diff --git a/crates/engine/src/tests/widthtool.rs b/crates/engine/src/tests/widthtool.rs index fda761de61..6b2ed12c54 100644 --- a/crates/engine/src/tests/widthtool.rs +++ b/crates/engine/src/tests/widthtool.rs @@ -40,6 +40,24 @@ fn the_width_tool_edits_a_compound_paths_stroke() { assert_eq!(s.journal.last().unwrap().1["id"], json!(c.0)); } +/// A compound path whose stroke draws with a brush: a press or a double-click on a member puts the +/// tool's reason in the status bar and leaves the stroke and the undo history as they were. +#[test] +fn the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone() { + let (mut s, c, _) = compound(); + s.execute("brush.apply", &json!({"ids": [c.0], "name": "3 pt. Round"})).unwrap(); + let steps = s.journal.len(); + let v = ViewInfo::default(); + s.select_tool("width", v).unwrap(); + for (kind, reason) in [(PointerKind::Down, true), (PointerKind::Drag, false), (PointerKind::Up, false), (PointerKind::DoubleClick, true)] { + let ui = s.pointer(&PointerEvent::new(kind, 200.0, 301.0), v).unwrap(); + let said = ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m == vectorcraft_tools::distort::KEEPS_SIZE)); + assert_eq!(said, reason, "{kind:?}: {ui:?}"); + } + assert_eq!(profile(&s, c), None); + assert_eq!(s.journal.len(), steps, "no command ran"); +} + #[test] fn width_point_commands_given_a_member_edit_the_compound() { let (mut s, c, members) = compound(); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 4e13e5fe02..a3470617a7 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -480,8 +480,8 @@ fn reflect_and_shear_tools() { assert!((b.width() - 150.0).abs() < 1e-6, "{b:?}"); } -/// Reflect and Shear return an error for an `axis` they don't take (Reflect's names it and also -/// takes an angle): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect +/// Reflect and Shear return an error for an `axis` they don't take, naming it (both also take an +/// angle, Shear's from -359° to 359°): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect /// then reflects across the vertical axis and Shear shears along the horizontal one. #[test] fn reflect_and_shear_reject_unknown_axes_without_changing_state() { @@ -489,13 +489,17 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() { let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); let n = undo_len(&s); let reflect = "axis must be \"vertical\", \"horizontal\" or an angle in degrees"; - let shear = "`axis` must be one of horizontal, vertical"; + let shear = "axis must be \"horizontal\", \"vertical\" or an angle in degrees from -359 to 359"; for (cmd, p, msg) in [ ("object.reflect", json!({"axis": "diagonal", "origin": [0, 0]}), format!("{reflect}, not `diagonal`")), ("object.reflect", json!({"axis": "45", "origin": [0, 0]}), format!("{reflect}, not `45`")), ("object.reflect", json!({"axis": true, "origin": [0, 0]}), format!("{reflect}, not `true`")), - ("object.shear", json!({"angle": 30, "axis": "diagonal"}), shear.to_string()), - ("object.shear", json!({"angle": 30, "axis": 90}), shear.to_string()), + ("object.shear", json!({"angle": 30, "axis": "diagonal"}), format!("{shear}, not `diagonal`")), + ("object.shear", json!({"angle": 30, "axis": "90"}), format!("{shear}, not `90`")), + ("object.shear", json!({"angle": 30, "axis": 360}), format!("{shear}, not `360`")), + ("object.shear", json!({"angle": 30, "axis": -359.5}), format!("{shear}, not `-359.5`")), + ("object.shear", json!({"angle": 30, "axis": [45]}), format!("{shear}, not `[45]`")), + ("object.shear", json!({"angle": 30, "axis": false}), format!("{shear}, not `false`")), ] { let e = s.execute(cmd, &p).expect_err(&format!("{cmd} {p}")); assert_eq!(e.to_string(), format!("invalid parameters for `{cmd}`: {msg}")); @@ -511,6 +515,119 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() { assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}"); } +/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant +/// opposite ways, and 120 and 300 slant as -60 does. +#[test] +fn shear_angles_slant_by_their_tangent() { + let run = 100.0 * 60f64.to_radians().tan(); + for (angle, want) in [ + (60.0, Rect::new(-run, 0.0, 100.0, 100.0)), + (-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)), + ] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap(); + assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a)); + } +} + +/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no +/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded. +#[test] +fn shear_rejects_angles_with_no_shear_or_out_of_range() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let n = undo_len(&s); + let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear"); + let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}"); + for (angle, msg) in [ + (90.0, none(90.0)), + (-90.0, none(-90.0)), + (270.0, none(270.0)), + (-270.0, none(-270.0)), + (90.0 + 1e-12, none(90.0 + 1e-12)), + (360.0, range(360.0)), + (-359.5, range(-359.5)), + (1e300, range(1e300)), + ] { + let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string()); + assert_eq!(e.to_string(), msg); + } + assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle"); + assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), n, "no undo step"); +} + +/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact +/// coordinates and no undo step is recorded. +#[test] +fn shear_by_0_and_180_changes_nothing() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let before = bounds(&s, a); + let n = undo_len(&s); + for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] { + for axis in ["horizontal", "vertical"] { + s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap(); + assert_eq!(bounds(&s, a), before, "{angle} {axis}"); + assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step"); + } + } +} + +/// Shear along an axis at an angle, counter-clockwise from horizontal on the page: each point +/// slides along the axis by the tangent of the shear angle times its distance across the axis +/// from the origin. -359° and 359° are taken, the shear is one undo step and Transform Again +/// repeats it; 0° and 90° shear as the named axes do, and a copy leaves the original in place. +#[test] +fn shear_along_an_axis_at_an_angle() { + let anchors = |s: &Session, id: NodeId| -> Vec { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect() + }; + // The axis's direction and the direction a quarter turn counter-clockwise from it, with y down. + let sheared = |p: Point, o: Point, axis: f64, angle: f64| { + let (a, k) = (axis.to_radians(), angle.to_radians().tan()); + let (along, across) = (Vec2::new(a.cos(), -a.sin()), Vec2::new(-a.sin(), -a.cos())); + p + along * (k * (p - o).dot(across)) + }; + let near = |a: &[Point], b: &[Point]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| p.distance(*q) < 1e-9); + let o = Point::new(20.0, 30.0); + for (axis, angle) in [(45.0, 30.0), (-120.5, 20.0), (359.0, 30.0), (-359.0, -30.0), (30.0, 30.0)] { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0); + let before = anchors(&s, a); + let n = undo_len(&s); + s.execute("object.shear", &json!({"angle": angle, "axis": axis, "origin": [o.x, o.y]})).unwrap(); + let want: Vec = before.iter().map(|p| sheared(*p, o, axis, angle)).collect(); + assert!(near(&anchors(&s, a), &want), "{axis}° {angle}°: {:?}, not {want:?}", anchors(&s, a)); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + s.execute("object.transformAgain", &json!({})).unwrap(); + let again: Vec = want.iter().map(|p| sheared(*p, o, axis, angle)).collect(); + assert!(near(&anchors(&s, a), &again), "Transform Again at {axis}°: {:?}", anchors(&s, a)); + } + for (named, axis) in [("horizontal", 0.0), ("vertical", 90.0), ("vertical", -270.0)] { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0); + s.execute("object.shear", &json!({"angle": 30, "axis": named, "origin": [o.x, o.y]})).unwrap(); + let by_name = anchors(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.shear", &json!({"angle": 30, "axis": axis, "origin": [o.x, o.y]})).unwrap(); + assert!(near(&anchors(&s, a), &by_name), "{axis}° shears as {named}: {:?}, not {by_name:?}", anchors(&s, a)); + } + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0); + let before = anchors(&s, a); + s.execute("object.shear", &json!({"angle": 30, "axis": 45, "origin": [o.x, o.y], "copy": true})).unwrap(); + assert!(near(&anchors(&s, a), &before), "the original stays: {:?}", anchors(&s, a)); + let copy = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_ne!(copy, a, "the copy is selected"); + let want: Vec = before.iter().map(|p| sheared(*p, o, 45.0, 30.0)).collect(); + assert!(near(&anchors(&s, copy), &want), "the copy is sheared: {:?}", anchors(&s, copy)); +} + #[test] fn distort_command_maps_corners() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 90a7c001e0..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 @@ -1321,7 +1331,14 @@ impl Session { /// The options of tool `id`: the active tool's, or those it would have if chosen now. pub fn tool_options_of(&self, id: &str) -> Value { - if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() } + if id == self.tool.id() { + self.tool.options() + } else if let Some(lender) = self.lender.as_deref().filter(|l| l.id() == id) { + // The tool that lent a selection tool for a Cmd-drag holds its options while it waits. + lender.options() + } else { + self.make_tool(id).options() + } } /// Set options of tool `id` (default: the active tool). Another tool's persistent options are @@ -1333,14 +1350,22 @@ impl Session { self.note_place_queue_roots(); } let active = id.is_none_or(|id| id == self.tool.id()); - self.tool_set_since_reset |= active; + // The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again + // when the drag ends. + let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id)); + self.tool_set_since_reset |= active || lender; + // The Place queue and a parametric shape's kind are set first: setting the queue starts + // again at its first file, and a `current` given with it is an index into it; setting the + // kind puts the shape's other numbers back to that kind's, and those given with it are its. + let first = |k: &str| k == "queue" || k == "kind"; + let ordered = || values.iter().filter(|(k, _)| first(k)).chain(values.iter().filter(|(k, _)| !first(k))); let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default())); let t = other.as_deref_mut().unwrap_or(self.tool.as_mut()); - for (k, v) in values { + for (k, v) in ordered() { t.set_option(k, v); } Self::store_tool_settings(&mut self.prefs, t); - let out = t.options(); + let mut out = t.options(); if let Some(other) = other { // The tool that lent a selection tool for a Cmd-drag is kept aside, not made again when // it is back: when it is the tool set, it takes the writes too (the Rounded Rectangle's @@ -1348,11 +1373,14 @@ impl Session { // active tool. if let Some(lender) = self.lender.as_deref_mut() { if lender.id() == other.id() { - for (k, v) in values { + for (k, v) in ordered() { lender.set_option(k, v); } } Self::restore_tool_settings(&self.prefs, lender); + if lender.id() == other.id() { + out = lender.options(); + } } // Only the stores it shares with the tool set: the active tool's own options stay as they // are, also in the middle of a drag that Escape can cancel. @@ -1364,21 +1392,28 @@ impl Session { /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: - /// the active tool) → its options. + /// the tool active when the call arrives, named before the edit in progress is finished) → its + /// options. With no option given, the options are read and nothing is set. Parameters that are + /// not an object are an error; none (null) read the options. Every option given is checked + /// first ([`vectorcraft_tools::Tool::check_option`]): an unknown option, a value of the wrong + /// type or a number out of range is an error that sets none of them. pub fn set_tool_option_cmd(&mut self, p: &Value) -> std::result::Result { - let tool = p.get("tool").and_then(Value::as_str); + let (tool, values) = vectorcraft_tools::option_check::set_option_params(p)?; if let Some(t) = tool && vectorcraft_tools::tool_info(t).is_none() { return Err(format!("unknown tool `{t}`")); } - let mut values = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default(); - if let Some(k) = p.get("key").and_then(Value::as_str) { - values.insert(k.to_string(), p.get("value").cloned().unwrap_or(Value::Null)); + // The tool is named before the edit in progress is finished: finishing it can make a held + // Cmd press, which lends a selection tool and makes that the active tool. + let id = tool.unwrap_or(self.tool.id()); + let active = id == self.tool.id(); + if values.is_empty() { + return Ok(self.tool_options_of(id)); } // Every value is checked before any is set, so an invalid one changes nothing. - vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; - if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { + vectorcraft_tools::builder::check_builder_options(id, &values)?; + if id == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; // The most the selected image can be cropped to, when one is selected. let max = self.doc().ok().and_then(|st| { @@ -1397,7 +1432,7 @@ impl Session { crate::file_access::check_read(path)?; } } - if tool.unwrap_or(self.tool_id()) == "dimension" { + if id == "dimension" { if let Some(style) = values.get("style") { vectorcraft_doc::dimension::DimensionOptions::from_params(style.clone())?; } @@ -1407,11 +1442,16 @@ impl Session { return Err("Unknown dimension mode".into()); } } + if active { + vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?; + } else { + vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?; + } // The active tool's merge being computed is applied with the options it was started with. - if tool.is_none_or(|t| t == self.tool.id()) { + if active { self.finish_tool_edit_later().map_err(|e| e.to_string())?; } - Ok(self.set_tool_options(tool, &values)) + Ok(self.set_tool_options(Some(id), &values)) } /// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]): diff --git a/crates/engine/tests/blend_render_consistency.rs b/crates/engine/tests/blend_render_consistency.rs new file mode 100644 index 0000000000..fdc2fb3b93 --- /dev/null +++ b/crates/engine/tests/blend_render_consistency.rs @@ -0,0 +1,200 @@ +//! Blend edits invalidate every pixel they change, including keys aligned to a curved spine. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{Document, NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Affine; +use vectorcraft_render::{Changed, RenderOptions, Rendered, Renderer, view_pixels}; + +const WIDTH: u32 = 720; +const HEIGHT: u32 = 480; + +type Retained = (Renderer, Option<(Arc, Vec)>); + +fn live(s: &Session, blend: NodeId, keys: [NodeId; 2], curved: bool) { + let doc = &s.doc().unwrap().doc; + let NodeKind::Blend { children, spec } = &doc.node(blend).unwrap().kind else { + panic!("INPUT: the fixture must remain a live blend"); + }; + assert_eq!(children.iter().map(|n| n.id).collect::>(), keys.to_vec()); + assert_eq!(serde_json::to_value(spec).unwrap()["spacing"], json!({"steps": 3})); + for key in keys { + assert_eq!(doc.parent_of(key), Some(blend), "INPUT: key identity/parent changed"); + } + if curved { + let bounds = spec.spine.as_ref().expect("INPUT: Replace Spine did not set a spine").bounds().unwrap(); + assert!(!spec.no_spine && bounds.height() > 40.0 && bounds.width() > 250.0, "INPUT: a real curved spine is required"); + } +} + +fn fixture() -> (Session, NodeId, [NodeId; 2]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap(); + let mut rectangle = |x: f64, color: &str| { + let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 120.0, "width": 64.0, "height": 48.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + id + }; + let keys = [rectangle(90.0, "#d52c38"), rectangle(430.0, "#25b453")]; + let blend = NodeId( + s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(), + ); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + live(&s, blend, keys, false); + (s, blend, keys) +} + +fn cpu() -> Renderer { + let mut renderer = Renderer::new(); + renderer.threads = 0; + renderer +} + +fn same_pixels(actual: &Rendered, expected: &Rendered) { + assert_eq!((actual.width, actual.height), (WIDTH, HEIGHT)); + assert_eq!((expected.width, expected.height), (WIDTH, HEIGHT)); + assert_eq!(actual.pixels.len(), (WIDTH * HEIGHT * 4) as usize); + assert!(actual.pixels == expected.pixels, "complete RGBA frames differ"); +} + +fn damage_pixels(stage: &str, changed: Changed, before: &[u8], current: &[u8]) { + let region = match changed { + Changed::Everything => return, + Changed::Nothing => None, + Changed::Area(area) => view_pixels(area, Affine::IDENTITY, WIDTH, HEIGHT), + }; + assert_eq!(before.len(), current.len()); + for (i, (old, new)) in before.as_chunks::<4>().0.iter().zip(current.as_chunks::<4>().0.iter()).enumerate() { + let (x, y) = (i as u32 % WIDTH, i as u32 / WIDTH); + if !region.is_some_and(|[x0, y0, x1, y1]| x >= x0 && x < x1 && y >= y0 && y < y1) { + assert_eq!(old, new, "{stage}: pixel ({x}, {y}) changed outside {changed:?}, view pixels {region:?}"); + } + } +} + +fn frame(s: &Session, retained: &mut Retained, stage: &str) -> Rendered { + let doc = &s.doc().unwrap().doc; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..Default::default() }; + // Ask for the edit's advertised damage before rendering the new full frame on this renderer. + let changed = retained.1.as_ref().map(|(old, _)| retained.0.changed(old.as_ref(), doc.as_ref(), &opts)); + let actual = retained.0.render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts); + let expected = cpu().render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts); + same_pixels(&actual, &expected); + let red = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] > 150 && p[1] < 100 && p[2] < 120 && p[3] == 255).count(); + let green = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] < 100 && p[1] > 120 && p[2] < 150 && p[3] == 255).count(); + assert!(red > 100 && green > 100, "INPUT: both original colored keys must really draw: red={red}, green={green}"); + if let (Some((_, previous)), Some(changed)) = (&retained.1, changed) { + damage_pixels(stage, changed, previous, &expected.pixels); + } + retained.1 = Some((doc.clone(), expected.pixels)); + actual +} + +fn move_and_undo(s: &mut Session, retained: &mut Retained, blend: NodeId, keys: [NodeId; 2], curved: bool, before_frame: &Rendered) { + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + s.execute("object.transform", &json!({"matrix": [1.0, 0.0, 0.0, 1.0, 37.0, 29.0]})).unwrap(); + live(s, blend, keys, curved); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let moved = frame(s, retained, "moved"); + assert!(moved.pixels != before_frame.pixels, "INPUT: the fresh rendered fixture must actually move"); + s.execute("edit.undo", &json!({})).unwrap(); + live(s, blend, keys, curved); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let restored = frame(s, retained, "undo-move"); + same_pixels(&restored, before_frame); +} + +#[test] +fn blend_5179_straight_move_undo_matches_fresh_cpu() { + let (mut s, blend, keys) = fixture(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "warm"); + move_and_undo(&mut s, &mut retained, blend, keys, false, &warm); +} + +#[test] +fn blend_5179_replace_spine_move_undo_matches_fresh_cpu() { + let (mut s, blend, keys) = fixture(); + let path = NodeId(s.execute("path.create", &json!({"d": "M122 144 C166 330 402 288 462 144"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap(); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + let nodes = s.doc().unwrap().doc.node_count(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "before-replace"); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + live(&s, blend, keys, true); + assert!(s.doc().unwrap().doc.node(path).is_none(), "Replace Spine consumes the original standalone path"); + assert_eq!(s.doc().unwrap().doc.node_count(), nodes - 1); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let replaced = frame(&s, &mut retained, "replaced"); + assert!(replaced.pixels != warm.pixels, "INPUT: replacing the spine must visibly change the drawn fixture"); + move_and_undo(&mut s, &mut retained, blend, keys, true, &replaced); + s.execute("edit.undo", &json!({})).unwrap(); + live(&s, blend, keys, false); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + let restored = frame(&s, &mut retained, "undo-replace"); + same_pixels(&restored, &warm); +} + +// A fixed ordinary anisotropic Transform, evaluated after Align to Path turns the key. +// 200% is the legitimate control; 400% is the single source-derived witness. +fn rotated_transform_damage(scale_h: f64) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap(); + let mut rectangle = |x: f64, color: &str| { + let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 200.0, "width": 8.0, "height": 80.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": scale_h, "scaleV": 100.0, "reference": 4}})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 8.0).abs() < 1e-8 && (b.height() - 80.0).abs() < 1e-8, "INPUT: the Transform must remain live on the narrow key"); + assert_eq!(n.appearance.effects.len(), 1); + assert_eq!(n.appearance.effects[0].params["scaleH"], json!(scale_h)); + id + }; + let keys = [rectangle(260.0, "#d52c38"), rectangle(460.0, "#25b453")]; + let blend = NodeId( + s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(), + ); + live(&s, blend, keys, false); + let path = NodeId(s.execute("path.create", &json!({"d": "M264 160 L264 320"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap(); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "anisotropic-before-replace"); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + live(&s, blend, keys, false); + assert!(s.doc().unwrap().doc.node(path).is_none()); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let n = s.doc().unwrap().doc.node(blend).unwrap(); + let NodeKind::Blend { spec, .. } = &n.kind else { panic!("INPUT: the fixture must remain a live blend") }; + let spine = spec.spine.as_ref().unwrap().bounds().unwrap(); + assert!(spine.width().abs() < 1e-8 && (spine.height() - 160.0).abs() < 1e-8, "INPUT: this is the fixed vertical rail"); + let expanded = vectorcraft_render::expand_live(n); + let placed = expanded.iter().find(|n| n.id == keys[0]).unwrap(); + let b = placed.geometric_bounds().unwrap(); + assert!((b.width() - 80.0).abs() < 1e-8 && (b.height() - 8.0).abs() < 1e-8, "INPUT: Align to Path must really turn the key by 90 degrees"); + assert_eq!(placed.appearance.effects.len(), 1); + assert_eq!(placed.appearance.effects[0].params["scaleH"], json!(scale_h)); + let replaced = frame(&s, &mut retained, &format!("rotated-transform-{scale_h}-replace")); + assert!(replaced.pixels != warm.pixels, "INPUT: the replacement must really change the painted frame"); + move_and_undo(&mut s, &mut retained, blend, keys, false, &replaced); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + let restored = frame(&s, &mut retained, "anisotropic-undo-replace"); + same_pixels(&restored, &warm); +} + +#[test] +fn blend_5179_rotated_transform_damage_contains_painted_pixels() { + // The control completes every render, move and history check before the witness runs. + rotated_transform_damage(200.0); + rotated_transform_damage(400.0); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 0451692f16..b8114f705c 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1009,6 +1009,11 @@ fn structured_junk() { ("addon.pathtools.expandDashes", json!({})), ("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})), + ("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})), @@ -1273,6 +1278,36 @@ fn polygon_properties_junk() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +/// A live line's Line Properties with junk values (the fixtures have no line), on a line, a line +/// whose ends meet and one at the coordinate limit: never a panic, and the document stays sound. +#[test] +fn line_properties_junk() { + let mut cases: Vec = vec![json!({"lineLength": 4.0e6, "lineAngle": 45})]; + for key in ["lineLength", "lineAngle"] { + for v in junk_values() { + cases.push(json!({ key: v })); + } + } + let mut failures = vec![]; + for (a, b) in [((10.0, 20.0), (110.0, 70.0)), ((50.0, 50.0), (50.0, 50.0)), ((-4.0e6, 4.0e6), (4.0e6, -4.0e6))] { + for p in &cases { + let mut s = Fixture::Multi.session(); + let Ok(_) = no_panic(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1}))) else { + continue; + }; + match catch_quiet(|| no_panic(s.execute("object.setLiveShape", p))) { + Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{a:?} {b:?}]: {m}")), + Ok(_) => { + if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) { + failures.push(format!("object.setLiveShape {p} [{a:?} {b:?}]: {e}")); + } + } + } + } + } + assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); +} + /// The params `fuzzed_calls_keep_documents_serializable` sends `c`: each key with each of the /// first junk values, a string under a file or folder key replaced by a location inside `path`'s /// folder. 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/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 23bbdb0bee..17391ae98a 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -95,6 +95,29 @@ fn apply_to_all_restyles_every_dimension_in_one_undo_step() { assert!(s.execute("dimension.applyToAll", &json!({"id":line})).is_err(), "not a dimension"); } +#[test] +fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() { + use vectorcraft_doc::Arrowhead; + let mut s = session(); + for (style, head) in + [("filled", Some(Arrowhead::Triangle)), ("open", Some(Arrowhead::TriangleOpen)), ("tick", Some(Arrowhead::Slash)), ("none", None)] + { + let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":style}}))["id"].as_u64().unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let heads: Vec<_> = n + .children() + .unwrap() + .iter() + .filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone()))) + .filter(|(a, b)| a.is_some() || b.is_some()) + .collect(); + match head { + Some(head) => assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style}: {heads:?}"), + None => assert!(heads.is_empty(), "{style}: {heads:?}"), + } + } +} + #[test] fn dimension_angles_circles_arcs_and_curves() { let mut s = session(); @@ -1933,6 +1956,149 @@ fn an_anchor_beside_a_drawn_dimension_takes_the_point() { assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()])); } +/// The Smart Guide lines a pointer move at (`x`, `y`) shows, as their ends. +fn guide_lines(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> Vec<(vectorcraft_geom::Point, vectorcraft_geom::Point)> { + use vectorcraft_engine::tools::Overlay; + s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap(); + s.overlays(view).into_iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some((a, b)) } else { None }).collect() +} + +/// An edge with anchors at x 100, 200 and 300, and a dimension from 100 to 200 placed 30 points +/// above it, with the Dimension tool active and nothing selected: the session and the dimension. +fn level_start(view: ViewInfo) -> (Session, u64) { + let pt = vectorcraft_geom::Point::new; + let mut s = session(); + run(&mut s, "path.create", json!({"d": "M100 200 L200 200 L300 200 L300 300 L100 300 Z"})); + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", view).unwrap(); + linear_click(&mut s, view, 100.0, 200.0); + linear_click(&mut s, view, 200.0, 200.0); + linear_click(&mut s, view, 150.0, 170.0); + let first = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + run(&mut s, "select.none", json!({})); + (s, first) +} + +/// The next dimension, from 200 to 300, placed with the pointer at `y`: where its line lies. +fn level_next(s: &mut Session, view: ViewInfo, y: f64) -> (vectorcraft_geom::Point, vectorcraft_geom::Point) { + linear_click(s, view, 200.0, 200.0); + linear_click(s, view, 300.0, 200.0); + linear_click(s, view, 250.0, y); + let id = s.doc().unwrap().selection.objects[0].0; + recipe(s, id).line_ends() +} + +/// A dimension placed next to another, with its line within the Smart Guides snapping tolerance of +/// the level of the other's parallel line, has its line on that level. A level further off, Smart +/// Guides off, a locked dimension or one that is not parallel leaves the line where the pointer +/// puts it. +#[test] +fn a_dimension_line_placed_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let off = ViewInfo { smart_guides: false, ..plain }; + let pt = vectorcraft_geom::Point::new; + // 2.5 points below the first line's level, and 3.5 above it: on the level. + for y in [172.5, 166.5] { + let (mut s, _) = level_start(plain); + assert_eq!(level_next(&mut s, plain, y), (pt(200.0, 170.0), pt(300.0, 170.0)), "pointer at y {y}"); + } + // 10 points off: where the pointer is. + let (mut s, _) = level_start(plain); + assert_eq!(level_next(&mut s, plain, 180.0), (pt(200.0, 180.0), pt(300.0, 180.0))); + // Smart Guides off: where the pointer is. + let (mut s, _) = level_start(off); + assert_eq!(level_next(&mut s, off, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5))); + // A locked dimension does not pull the line. + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "object.lock", json!({})); + assert_eq!(level_next(&mut s, plain, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5))); + // A dimension of the right edge has a vertical line, which is not parallel to the first: the + // pointer 2.5 points below the first line's level places it where the pointer is. + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 300.0, 200.0); + linear_click(&mut s, plain, 300.0, 300.0); + linear_click(&mut s, plain, 330.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(330.0, 200.0), pt(330.0, 300.0))); +} + +/// While a dimension is placed with its line on the level of another, one alignment guide runs +/// along the level across both lines. Off the level, after a dropped press and with Alignment +/// Guides off, no guide shows. +#[test] +fn a_dimension_line_on_another_level_shows_one_guide_across_both() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + let guides = guide_lines(&mut s, plain, 250.0, 172.5); + assert!(guides.iter().any(|(a, b)| near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}"); + assert!(guide_lines(&mut s, plain, 250.0, 180.0).is_empty(), "no guide off the level"); + // A press on the level that the app drops cancels the preview, and its guide goes with it. + assert!(!guide_lines(&mut s, plain, 250.0, 172.5).is_empty()); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 172.5), plain).unwrap(); + s.drop_tool_press(plain).unwrap(); + assert!(s.overlays(plain).iter().all(|o| !matches!(o, vectorcraft_engine::tools::Overlay::Line { .. })), "{:?}", s.overlays(plain)); + // Alignment Guides off: the line still lands on the level, with no guide. + let (mut s, _) = level_start(plain); + run(&mut s, "prefs.set", json!({"key": "alignmentGuides", "value": false})); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + assert!(guide_lines(&mut s, plain, 250.0, 172.5).is_empty()); + linear_click(&mut s, plain, 250.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0))); +} + +/// A second dimension of the same two points as a dimension already drawn lands on its level too. +/// Off every level, a pointer moved in small steps while it is placed puts the line at each step, +/// with no pull from the preview of the dimension itself. +#[test] +fn a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + linear_click(&mut s, plain, 100.0, 200.0); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 150.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_ne!(id, first); + assert_eq!(recipe(&s, id).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + for y in [190.0, 189.0, 188.0, 187.0, 186.0] { + s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, y), plain).unwrap(); + } + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 250.0, 186.0), plain).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 186.0), pt(300.0, 186.0))); +} + +/// A dimension dragged out from a segment, with its line within the Smart Guides snapping +/// tolerance of the level of another dimension's parallel line, lands on that level. +#[test] +fn a_dimension_dragged_out_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + // The bottom edge dragged out to 2 points below the level of the first line, 130 points + // above the edge: on the level. + let (mut s, _) = level_start(plain); + for (kind, y) in + [(PointerKind::Move, 300.0), (PointerKind::Down, 300.0), (PointerKind::Drag, 240.0), (PointerKind::Drag, 172.0), (PointerKind::Up, 172.0)] + { + s.pointer(&PointerEvent::new(kind, 160.0, y), plain).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0].0; + let (a, b) = recipe(&s, id).line_ends(); + assert!(near(a, pt(300.0, 170.0)) && near(b, pt(100.0, 170.0)) || near(a, pt(100.0, 170.0)) && near(b, pt(300.0, 170.0)), "{a:?} {b:?}"); +} + /// The page content streams of exported PDF `v`, inflated. fn pdf_content(v: &Value) -> String { let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); @@ -1971,9 +2137,15 @@ fn dimension_colours_follow_the_document_colour_model() { let black = colours(&s, id); assert!(!black.is_empty() && black.iter().all(|c| *c == vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0)), "{black:?}"); let pdf = pdf_content(&run(&mut s, "document.exportPdf", json!({"preset":"PDF/X-4:2010"}))); - // PDF/X-4 paints in the output intent's CMYK space: `/c0 CS 0 0 0 1 SCN` strokes, `scn` fills. - let operands = |op: &str| pdf.match_indices(op).map(|(i, _)| pdf[i.saturating_sub(7)..i].to_string()).collect::>(); - let (strokes, fills) = (operands(" SCN"), operands(" scn")); + // PDF/X-4 writes CMYK in the output intent's profile as DeviceCMYK: `0 0 0 1 K` strokes, `k` fills. + let words: Vec<&str> = pdf.split_whitespace().collect(); + let operands = |op: &str| { + (4..words.len()) + .filter(|&i| words[i] == op && words[i - 4..i].iter().all(|w| w.parse::().is_ok())) + .map(|i| words[i - 4..i].join(" ")) + .collect::>() + }; + let (strokes, fills) = (operands("K"), operands("k")); assert!(!strokes.is_empty() && !fills.is_empty(), "{pdf}"); assert!(strokes.iter().chain(&fills).all(|v| v == "0 0 0 1"), "K-only colours: {strokes:?} {fills:?}"); run(&mut s, "dimension.update", json!({"ids":[id],"options":{"lineColor":[255,0,0]}})); diff --git a/crates/engine/tests/path_fill_hits.rs b/crates/engine/tests/path_fill_hits.rs new file mode 100644 index 0000000000..f8dfebafaf --- /dev/null +++ b/crates/engine/tests/path_fill_hits.rs @@ -0,0 +1,244 @@ +//! Path fill hit testing follows the visible paint stack while transparent paint remains selectable. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; +use vectorcraft_render::{RenderOptions, Renderer}; + +fn fill(paint: Paint) -> FillLayer { + FillLayer::new(paint) +} + +fn rectangle(fills: Vec, stroke: bool) -> Document { + let mut doc = Document::new(128.0, 128.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + if stroke { + appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))); + } + let path = shapes::rectangle(Rect::new(20.0, 20.0, 100.0, 100.0)); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + doc +} + +fn compound(fills: Vec) -> Document { + let mut doc = Document::new(128.0, 128.0); + let layer = doc.layers[0].id; + let outer_id = doc.alloc_id(); + let inner_id = doc.alloc_id(); + let compound_id = doc.alloc_id(); + let children = vec![ + Arc::new(Node::path(outer_id, shapes::rectangle(Rect::new(20.0, 20.0, 100.0, 100.0)), Appearance::default())), + Arc::new(Node::path(inner_id, shapes::rectangle(Rect::new(50.0, 40.0, 70.0, 80.0)), Appearance::default())), + ]; + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))); + let mut node = Node::new(compound_id, NodeKind::Compound { children, rule: FillRule::EvenOdd }); + node.appearance = appearance.into(); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + doc +} + +#[test] +fn hit_uses_the_visible_fill_stack() { + let black = || fill(Paint::solid(Color::BLACK)); + + let mut hidden = black(); + hidden.visible = false; + let mut transparent = black(); + transparent.opacity = 0.0; + let mut hidden_lower = black(); + hidden_lower.visible = false; + + let cases = vec![ + ("visible black fill", rectangle(vec![black()], true)), + ("lower black fill under a top None fill", rectangle(vec![black(), fill(Paint::None)], true)), + ("lower black fill under a top None fill without stroke", rectangle(vec![black(), fill(Paint::None)], false)), + ("only hidden non-None fill", rectangle(vec![hidden], true)), + ("basic Fill None", rectangle(vec![fill(Paint::None)], true)), + ("hidden lower black and top None fills", rectangle(vec![hidden_lower, fill(Paint::None)], true)), + ("visible fill at zero opacity", rectangle(vec![transparent], true)), + ]; + + let mut observed = Vec::new(); + for (name, doc) in cases { + let image = Renderer::new().render( + &doc, + 128, + 128, + Affine::IDENTITY, + &RenderOptions { background: None, artboards: false, ..RenderOptions::default() }, + ); + let center_alpha = image.pixel(60, 60)[3]; + let edge_alpha = image.pixel(100, 60)[3]; + let center = hit_test(&doc, Point::new(60.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let edge = hit_test(&doc, Point::new(100.5, 60.0), HitOptions::default()).map(|hit| hit.kind); + let outline = hit_test(&doc, Point::new(60.0, 60.0), HitOptions { outline: true, ..HitOptions::default() }).map(|hit| hit.kind); + let path_only = hit_test(&doc, Point::new(60.0, 60.0), HitOptions { path_only: true, ..HitOptions::default() }).map(|hit| hit.kind); + observed.push((name, center_alpha, edge_alpha, center, edge, outline, path_only)); + } + + let expected = vec![ + ("visible black fill", 255, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill", 255, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill without stroke", 255, 0, Some(HitKind::Fill), Some(HitKind::Outline), None, None), + ("only hidden non-None fill", 0, 255, None, Some(HitKind::Stroke), None, None), + ("basic Fill None", 0, 255, None, Some(HitKind::Stroke), None, None), + ("hidden lower black and top None fills", 0, 255, None, Some(HitKind::Stroke), None, None), + ("visible fill at zero opacity", 0, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ]; + assert_eq!(observed, expected, "render and hit-test observations by fill-stack case"); +} + +#[test] +fn compound_hit_uses_visible_fill_stack() { + let black = || fill(Paint::solid(Color::BLACK)); + + let mut hidden = black(); + hidden.visible = false; + let mut transparent = black(); + transparent.opacity = 0.0; + + let cases = vec![ + ("visible black fill", compound(vec![black()])), + ("lower black fill under a top None fill", compound(vec![black(), fill(Paint::None)])), + ("only hidden non-None fill", compound(vec![hidden])), + ("basic Fill None", compound(vec![fill(Paint::None)])), + ("visible fill at zero opacity", compound(vec![transparent])), + ]; + + let mut observed = Vec::new(); + for (name, doc) in cases { + let image = Renderer::new().render( + &doc, + 128, + 128, + Affine::IDENTITY, + &RenderOptions { background: None, artboards: false, ..RenderOptions::default() }, + ); + let ring_alpha = image.pixel(30, 60)[3]; + let hole_alpha = image.pixel(60, 60)[3]; + let edge_alpha = image.pixel(100, 60)[3]; + let ring = hit_test(&doc, Point::new(30.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let hole = hit_test(&doc, Point::new(60.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let edge = hit_test(&doc, Point::new(100.5, 60.0), HitOptions::default()).map(|hit| hit.kind); + let outline = hit_test(&doc, Point::new(30.0, 60.0), HitOptions { outline: true, ..HitOptions::default() }).map(|hit| hit.kind); + let path_only = hit_test(&doc, Point::new(30.0, 60.0), HitOptions { path_only: true, ..HitOptions::default() }).map(|hit| hit.kind); + observed.push((name, ring_alpha, hole_alpha, edge_alpha, ring, hole, edge, outline, path_only)); + } + + let expected = vec![ + ("visible black fill", 255, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill", 255, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ("only hidden non-None fill", 0, 0, 255, None, None, Some(HitKind::Stroke), None, None), + ("basic Fill None", 0, 0, 255, None, None, Some(HitKind::Stroke), None, None), + ("visible fill at zero opacity", 0, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ]; + assert_eq!(observed, expected, "render and hit-test observations by Compound fill-stack case"); +} + +#[test] +fn hit_respects_open_stroke_caps_with_hidden_fill() { + use vectorcraft_doc::{LineCap, LineJoin}; + use vectorcraft_geom::{BezPath, PathData}; + + let mut observed = Vec::new(); + let mut expected = Vec::new(); + // Round and Square are legitimate controls before the Butt regression. + for (cap, endpoint_pixel, endpoint_hit) in [ + (LineCap::Round, [0, 0, 0, 255], Some(HitKind::Stroke)), + (LineCap::Square, [0, 0, 0, 255], Some(HitKind::Stroke)), + (LineCap::Butt, [255, 255, 255, 255], None), + ] { + for join in [LineJoin::Miter, LineJoin::Round] { + let mut hidden = fill(Paint::solid(Color::BLACK)); + hidden.visible = false; + for (name, fills) in [ + ("hidden painted fill", vec![hidden]), + ("absent fill", vec![]), + ("explicit Fill None", vec![fill(Paint::None)]), + ("visible fill on a zero-area line", vec![fill(Paint::solid(Color::BLACK))]), + ] { + let mut doc = Document::new(160.0, 96.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 10.0); + stroke.cap = cap; + stroke.join = join; + appearance.items.push(AppearanceItem::Stroke(stroke)); + let path = PathData::from_bezpath(&BezPath::from_svg("M24 48 L124 48").unwrap()); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + let image = renderer.render( + &doc, + 160, + 96, + Affine::IDENTITY, + &RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..RenderOptions::default() }, + ); + let options = HitOptions { tol: 0.5, ..HitOptions::default() }; + let end = hit_test(&doc, Point::new(20.0, 48.0), options).map(|hit| hit.kind); + let body = hit_test(&doc, Point::new(60.0, 48.0), options).map(|hit| hit.kind); + assert_eq!(image.pixel(60, 48), [0, 0, 0, 255], "INPUT: {cap:?}/{join:?}/{name} stroke body must draw"); + assert_eq!(body, Some(HitKind::Stroke), "INPUT: {cap:?}/{join:?}/{name} stroke body must hit"); + observed.push((cap, join, name, image.pixel(20, 48), end, image.pixel(60, 48), body)); + expected.push((cap, join, name, endpoint_pixel, endpoint_hit, [0, 0, 0, 255], Some(HitKind::Stroke))); + } + } + } + assert_eq!(observed, expected, "visible stroke caps and hit testing must agree, including hidden-fill paths"); +} + +#[test] +fn hit_respects_hidden_fill_stroke_joins() { + use vectorcraft_doc::{LineCap, LineJoin}; + use vectorcraft_geom::{BezPath, PathData}; + + let mut observed = Vec::new(); + let mut expected = Vec::new(); + for (join, joint_painted, joint_hit) in + [(LineJoin::Round, true, Some(HitKind::Stroke)), (LineJoin::Miter, true, Some(HitKind::Stroke)), (LineJoin::Bevel, false, None)] + { + let mut doc = Document::new(160.0, 96.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut hidden = fill(Paint::solid(Color::BLACK)); + hidden.visible = false; + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Fill(hidden)); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 10.0); + stroke.cap = LineCap::Round; + stroke.join = join; + appearance.items.push(AppearanceItem::Stroke(stroke)); + let path = PathData::from_bezpath(&BezPath::from_svg("M32 64 L96 64 L96 24").unwrap()); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + let image = renderer.render( + &doc, + 160, + 96, + Affine::IDENTITY, + &RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..RenderOptions::default() }, + ); + let options = HitOptions { tol: 0.5, ..HitOptions::default() }; + let joint = hit_test(&doc, Point::new(99.0, 67.0), options).map(|hit| hit.kind); + let body = hit_test(&doc, Point::new(60.0, 64.0), options).map(|hit| hit.kind); + assert_eq!(image.pixel(60, 64), [0, 0, 0, 255], "INPUT: {join:?} stroke body must draw"); + assert_eq!(body, Some(HitKind::Stroke), "INPUT: {join:?} stroke body must hit"); + // Round's corner pixel can be antialiased; only its visible paint is required. + observed.push((join, image.pixel(99, 67) != [255, 255, 255, 255], joint)); + expected.push((join, joint_painted, joint_hit)); + } + assert_eq!(observed, expected, "hidden-fill stroke joins must match actual CPU paint at the outer joint"); +} diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index cc39566875..a8de5429dc 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -287,3 +287,107 @@ fn a_cancelled_export_stops_the_exporter() { assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}"); } + +/// Every string in `v`, at any depth. +fn strings_in(v: &Value, out: &mut Vec) { + match v { + Value::String(s) => out.push(s.clone()), + Value::Array(items) => items.iter().for_each(|v| strings_in(v, out)), + Value::Object(map) => map.values().for_each(|v| strings_in(v, out)), + _ => {} + } +} + +/// A confined caller: an exporter, given the native document's JSON, is not run for a document +/// that links a JavaScript file, a data set's image or a placed file outside the read roots. Every +/// command that writes its format refuses, before any file or folder is written, with an error +/// that names no file or folder, and the document keeps its links. A data set's image inside the +/// roots is given to it, the JSON it is given leaves out an Export for Screens folder outside them, +/// and the person's export gives it every path as stored. +#[test] +fn a_confined_exporter_is_refused_stored_paths_outside_the_read_roots() { + use vectorcraft_engine::file_access::{AutomationRoots, confine}; + + let away = tmp_dir("confined-away"); + let home = tmp_dir("confined-home"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("assets.add", &json!({"ids": [r["id"]]})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.confined", r#"["tsc"]"#, "{}"), Echo::Input)); + let format = "plugin.test.confined"; + let roots = AutomationRoots::new(&[home.as_path()], &[home.as_path()]).unwrap(); + let out = path_of(&home.join("out")); + let outputs = [ + ("document.serialize", json!({"format": format})), + ("document.export", json!({"format": format})), + ("document.export", json!({"format": format, "path": path_of(&home.join("export.tsc"))})), + ("document.exportSelection", json!({"format": format})), + ("document.exportForScreens", json!({"folder": out, "formats": [{"format": format}]})), + ("assets.export", json!({"folder": out, "formats": [{"format": format}]})), + ]; + let hidden = [path_of(&away), path_of(&home)]; + // `assets`: an asset's file is checked too (its document holds the asset's art and the + // document's data sets, not other art). + let refused = |s: &mut Session, why: &str, assets: bool| { + for (cmd, p) in outputs.iter().filter(|(cmd, _)| assets || *cmd != "assets.export") { + let e = confine(roots.as_ref(), || s.execute(cmd, p)).expect_err(&format!("{cmd} {p}: {why}")); + assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains(why), "{cmd} {p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}"); + } + } + assert_eq!(std::fs::read_dir(&home).unwrap().count(), 0, "nothing is written"); + }; + // The strings of the JSON the exporter is given. + let given = |s: &mut Session, confined: bool| { + let p = json!({"format": format}); + let r = if confined { confine(roots.as_ref(), || s.execute("document.export", &p)) } else { s.execute("document.export", &p) }; + let mut found = vec![]; + strings_in(&serde_json::from_slice(&exported(&r.unwrap())).unwrap(), &mut found); + found + }; + + let script = path_of(&away.join("menu.js")); + s.execute("svgInteractivity.addFile", &json!({"file": script})).unwrap(); + refused(&mut s, "a linked JavaScript file is outside the read roots", true); + assert!(given(&mut s, false).contains(&script), "the person's export"); + s.execute("svgInteractivity.removeFile", &json!({"file": script})).unwrap(); + + let set_image = |s: &mut Session, path: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect(); + doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }]; + }; + let photo = path_of(&away.join("photo.png")); + set_image(&mut s, &photo); + refused(&mut s, "a linked image file is outside the read roots", true); + assert!(given(&mut s, false).contains(&photo), "the person's export"); + let inside = path_of(&home.join("photo.png")); + set_image(&mut s, &inside); + assert!(given(&mut s, true).contains(&inside), "an image inside the read roots"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.clear(); + + let folder = path_of(&away.join("screens")); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap(); + assert!(!given(&mut s, true).contains(&folder), "the export folder is left out"); + assert!(given(&mut s, false).contains(&folder), "the person's export"); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder"), Some(&json!(folder)), "the document keeps it"); + + let mut part = Session::new(); + part.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = path_of(&away.join("part.vectorcraft")); + part.execute("file.saveAs", &json!({"path": placed})).unwrap(); + s.execute("file.place", &json!({"path": placed, "link": true})).unwrap(); + refused(&mut s, "a linked image file is outside the read roots", false); + // The asset's file holds the rectangle alone, without the placed file. + let r = confine(roots.as_ref(), || s.execute("assets.export", &outputs[5].1)).unwrap(); + let mut found = vec![]; + strings_in(&serde_json::from_slice(&std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap(), &mut found); + assert!(!found.contains(&placed), "{found:?}"); + let _ = std::fs::remove_dir_all(&away); + let _ = std::fs::remove_dir_all(&home); +} diff --git a/crates/engine/tests/preflight.rs b/crates/engine/tests/preflight.rs new file mode 100644 index 0000000000..08b7cf153b --- /dev/null +++ b/crates/engine/tests/preflight.rs @@ -0,0 +1,216 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +//! Production preflight must find actual delivery problems and clear them after repairs. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +fn new() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({ "width": 500, "height": 400 })).unwrap(); + s +} + +fn check(s: &mut Session) -> Value { + s.execute("document.preflight", &json!({})).unwrap() +} + +fn codes(report: &Value) -> Vec<&str> { + report["findings"].as_array().unwrap().iter().map(|f| f["code"].as_str().unwrap()).collect() +} + +#[test] +fn preflight_finds_four_problems_and_repairs_clear_each_one() { + let dir = Folder::new("preflight-four"); + let path = dir.file("picture.png"); + let bytes = png(40, 40, [200, 50, 10]); + std::fs::write(&path, &bytes).unwrap(); + let mut s = new(); + let text = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight Missing Family 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone(); + let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200], "link": true })).unwrap()["ids"][0].clone(); + std::fs::remove_file(&path).unwrap(); + let before_doc = s.doc().unwrap().doc.clone(); + let before_sel = s.doc().unwrap().selection.clone(); + let revision = s.doc().unwrap().revision; + let report = check(&mut s); + for code in ["missingFont", "overflow", "missingLink", "lowResolution"] { + assert!(codes(&report).contains(&code), "{code}: {report}"); + } + assert_eq!(*before_doc, *s.doc().unwrap().doc); + assert_eq!(before_sel, s.doc().unwrap().selection); + assert_eq!(revision, s.doc().unwrap().revision, "checking doesn't edit the document"); + for f in report["findings"].as_array().unwrap() { + assert!(f["ids"].as_array().unwrap().iter().all(|id| id == &text || id == &image), "{f}"); + } + s.execute("text.areaOptions", &json!({ "ids": [text], "height": 150 })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"overflow")); + std::fs::write(&path, &bytes).unwrap(); + s.execute("links.update", &json!({ "ids": [image] })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"missingLink")); + s.execute("select.set", &json!({ "ids": [image] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 7.2, "height": 7.2 })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"lowResolution")); + // Deleting the missing-font object fixes the final delivery issue on any machine, including + // builds with no optional craft-fonts checkout or installed fonts. + s.execute("select.set", &json!({ "ids": [text] })).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let clean = check(&mut s); + assert!(codes(&clean).is_empty(), "{clean}"); + assert!(clean["checks"].as_array().unwrap().iter().all(|c| c["status"] == "passed")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(codes(&check(&mut s)).contains(&"missingFont"), "undo is checked too"); +} + +#[test] +fn preflight_reuses_link_probes_for_external_changes_without_an_edit() { + let dir = Folder::new("preflight-modified"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap(); + let mut s = new(); + let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200] })).unwrap()["ids"][0].clone(); + let rev = s.doc().unwrap().revision; + std::fs::write(&path, png(41, 45, [10, 50, 200])).unwrap(); + assert!(codes(&check(&mut s)).contains(&"modifiedLink")); + assert_eq!(rev, s.doc().unwrap().revision); + s.execute("links.update", &json!({ "ids": [image] })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"modifiedLink")); +} + +#[test] +fn preflight_scopes_artboards_and_respects_hidden_and_nonprinting_layers() { + let mut s = new(); + let id = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Scope 917" })).unwrap()["id"].clone(); + s.execute("artboard.new", &json!({ "x": 600, "y": 0, "width": 500, "height": 400 })).unwrap(); + let other = s.execute("document.preflight", &json!({ "artboards": [1] })).unwrap(); + assert!(codes(&other).is_empty(), "{other}"); + assert!(codes(&check(&mut s)).contains(&"missingFont")); + s.execute("object.setProps", &json!({ "ids": [id], "visible": false })).unwrap(); + assert!(codes(&check(&mut s)).is_empty()); + s.execute("object.setProps", &json!({ "ids": [id], "visible": true, "locked": true })).unwrap(); + assert!(codes(&check(&mut s)).contains(&"missingFont"), "locked artwork still exports"); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.setProps", &json!({ "id": layer.0, "printable": false })).unwrap(); + let print = s.execute("document.preflight", &json!({ "output": "print" })).unwrap(); + assert!(codes(&print).is_empty(), "{print}"); +} + +#[test] +fn preflight_resolution_follows_placed_size_and_both_axes() { + let dir = Folder::new("preflight-resolution"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap(); + let mut s = new(); + let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone(); + s.execute("select.set", &json!({ "ids": [id] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 24, "height": 72 })).unwrap(); + let r = check(&mut s); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["effectivePpi"], json!([300.0, 100.0])); + let screen = s.execute("document.preflight", &json!({ "output": "screen" })).unwrap(); + assert_eq!(screen["minPpi"], 96.0); + assert!(codes(&screen).is_empty(), "{screen}"); +} + +#[test] +fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() { + let dir = Folder::new("preflight-resolution-boundary"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap(); + let mut s = new(); + s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap(); + for threshold in [31.0, 59.0, 300.0, 600.0, 9600.0] { + let size = 40.0 * 72.0 / threshold; + s.execute("object.setBounds", &json!({ "width": size, "height": size })).unwrap(); + let exact = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap(); + assert!(!codes(&exact).contains(&"lowResolution"), "exactly {threshold} ppi: {exact}"); + s.execute("object.setBounds", &json!({ "width": size * 1.000001, "height": size })).unwrap(); + let below = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap(); + let f = below["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["threshold"], threshold); + } +} + +#[test] +fn preflight_resolution_includes_the_print_jobs_scale() { + let dir = Folder::new("preflight-print-scale"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap(); + let mut s = new(); + s.execute("file.place", &json!({ "path": path, "link": false, "at": [250, 200] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap(); + let doc = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap(); + assert!(codes(&doc).is_empty(), "{doc}"); + s.execute("print.setup", &json!({ "settings": { "scaling": "custom", "scale": { "width": 200, "height": 200 } } })).unwrap(); + let print = s.execute("document.preflight", &json!({ "output": "print", "minPpi": 200 })).unwrap(); + let f = print["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["effectivePpi"], json!([150.0, 150.0])); +} + +#[test] +fn preflight_reports_a_frame_that_cannot_show_even_its_first_line() { + let mut s = new(); + let id = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Abc", "size": 30, "area": { "width": 100, "height": 1 } })).unwrap()["id"] + .clone(); + let r = check(&mut s); + assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}"); +} + +#[test] +fn preflight_reports_type_that_cannot_place_a_glyph_on_a_horizontal_path() { + let mut s = new(); + let path = s.execute("path.create", &json!({ "d": "M10 20 L11 20" })).unwrap()["id"].clone(); + let id = s.execute("text.createInPath", &json!({ "path": path, "mode": "onPath", "text": "Longer than the path" })).unwrap()["id"].clone(); + let r = check(&mut s); + assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}"); +} + +#[test] +fn preflight_bad_options_leave_document_and_selection_unchanged() { + let mut s = new(); + let doc = s.doc().unwrap().doc.clone(); + for p in [ + json!({ "output": "unknown" }), + json!({ "output": 1 }), + json!({ "minPpi": 0 }), + json!({ "minPpi": "300" }), + json!({ "artboards": [] }), + json!({ "artboards": [0.5] }), + json!({ "artboards": [999] }), + ] { + assert!(s.execute("document.preflight", &p).is_err(), "{p}"); + assert_eq!(*doc, *s.doc().unwrap().doc); + } +} + +#[test] +fn preflight_resource_font_finding_locates_its_instance() { + let mut s = new(); + let text = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Symbol 917" })).unwrap()["id"].clone(); + s.execute("select.set", &json!({ "ids": [text] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Label" })).unwrap(); + let r = check(&mut s); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "missingFont").unwrap(); + assert!(f["ids"].as_array().unwrap().iter().all(|id| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some()), "{r}"); +} + +struct Folder(std::path::PathBuf); +impl Folder { + fn new(name: &str) -> Self { + Self(vectorcraft_testkit::temp_dir(name)) + } + fn file(&self, name: &str) -> String { + self.0.join(name).to_string_lossy().into_owned() + } +} +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} +fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + let pixels = (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect(); + let image = + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap(); + craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &Default::default()).unwrap() +} diff --git a/crates/engine/tests/text_import_fuzz.rs b/crates/engine/tests/text_import_fuzz.rs index 1ea656a158..c8417b73fc 100644 --- a/crates/engine/tests/text_import_fuzz.rs +++ b/crates/engine/tests/text_import_fuzz.rs @@ -17,7 +17,9 @@ proptest! { fn any_bytes_place_as_text_without_panics( bytes in prop::collection::vec(prop_oneof![any::(), Just(b'\r'), Just(b'\n'), Just(b' ')], 0..400), bom in prop::sample::select(vec![&b""[..], b"\xEF\xBB\xBF", b"\xFF\xFE", b"\xFE\xFF"]), - ansi in any::(), + set in prop::sample::select(vec![ + "unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean", + ]), mac in any::(), lines in any::(), paras in any::(), @@ -31,7 +33,7 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let text = json!({ - "characterSet": if ansi { "ansi" } else { "unicode" }, + "characterSet": set, "platform": if mac { "mac" } else { "windows" }, "removeLineReturns": lines, "removeParagraphReturns": paras, diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index aafdcac247..3c2b229e1f 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3431,6 +3431,133 @@ fn many_gradient_definitions_take_distinct_names_in_order() { assert_eq!(text, program(&doc)); } +/// The program written from `doc`, with the gradient and pattern definitions found by comparing +/// each in turn (`scanned`) or through their indexes. +fn program_scanned(doc: &Document, scanned: bool) -> Vec { + writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned)); + let out = export_ai_editing(doc, &opts()); + writer::SCANNED_DEFINITIONS.with(|s| s.set(false)); + out.unwrap().program +} + +/// [`gradients_and_patterns`] with more rectangles, each filled with a gradient: `distinct` with +/// gradients of their own; `reused` with one of `ramps` gradients in turn; one for each of +/// `swatches` new gradient swatches, linked to it, with the swatch's gradient for every other one +/// and another gradient for the rest; one with the gradient of an object whose style isn't written +/// (an even-odd fill with a drop shadow), after that object; and two whose gradients +/// differ only in the sign of a zero offset. +fn many_gradients(distinct: u16, reused: u16, ramps: u16, swatches: u16) -> Document { + let mut doc = gradients_and_patterns(); + let two = |a: Color, b: Color| ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]); + let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1)); + let swatch_gradient = |i: u16| two(Color::gray(shade(i, swatches)), Color::rgb(1.0, 0.0, 0.0)); + let more = (0..swatches) + .map(|i| Swatch { name: format!("Ramp {i}"), paint: gradient_paint(swatch_gradient(i), None, None), global: false, spot: false }) + .collect(); + swatches_plus(&mut doc, more); + let mut paints = vec![]; + for i in 0..distinct { + paints.push(gradient_paint(two(Color::rgb(shade(i, distinct), 0.5, 0.0), Color::rgb(0.0, 0.0, 1.0)), None, None)); + } + for i in 0..reused { + paints.push(gradient_paint(two(Color::rgb(0.0, shade(i % ramps.max(1), ramps), 0.5), Color::WHITE), None, None)); + } + for i in 0..swatches { + let g = if i % 2 == 0 { swatch_gradient(i) } else { two(Color::gray(shade(i, swatches)), Color::rgb(0.0, 1.0, 0.0)) }; + paints.push(gradient_paint(g, None, Some(&format!("Ramp {i}")))); + } + // The reader wouldn't read an even-odd fill with the style, so the style isn't written. + let unstyled = two(Color::WHITE, Color::BLACK); + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(unstyled.clone(), None, None)))], + effects: vec![fx("stylize.dropShadow", serde_json::json!({}))], + contents_index: None, + }; + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + if let NodeKind::Path { rule, .. } = &mut n.kind { + *rule = FillRule::EvenOdd; + } + put(&mut doc, n); + paints.push(gradient_paint(unstyled, None, None)); + let zero = |o: f32| ramp(GradientKind::Linear, &[(o, Color::rgb(0.2, 0.3, 0.4), 1.0, 0.5), (1.0, Color::BLACK, 1.0, 0.5)]); + paints.extend([gradient_paint(zero(0.0), None, None), gradient_paint(zero(-0.0), None, None)]); + for (i, p) in (0u16..).zip(paints) { + let (x, y) = (f64::from(i % 60) * 5.0, f64::from(i / 60 % 40) * 5.0); + let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), vec![AppearanceItem::Fill(FillLayer::new(p))]); + put(&mut doc, n); + } + doc +} + +/// Gradient and pattern definitions found through their indexes are those found by comparing each +/// in turn: the program is the same, byte for byte. A swatch's definition serves a paint linked to +/// it only with the swatch's gradient; a gradient defined for a style that isn't written leaves its +/// name free; gradients that differ only in the sign of a zero share a definition. +#[test] +fn indexed_definitions_write_the_same_program() { + let doc = many_gradients(300, 300, 7, 6); + let (indexed, scanned) = (program_scanned(&doc, false), program_scanned(&doc, true)); + let differ = indexed.iter().zip(&scanned).position(|(a, b)| a != b); + assert!(indexed == scanned, "the programs differ from byte {differ:?} ({} and {} bytes)", indexed.len(), scanned.len()); + let text = String::from_utf8(indexed).unwrap(); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + // `gradients_and_patterns`'s 5, then 300 + 7 + 6 swatches' + 3 others linked to swatches + 1 + // after the style + 1 for both signs of zero. + assert_eq!(names.len(), 5 + 300 + 7 + 6 + 3 + 1 + 1, "{names:?}"); + assert_eq!(names.iter().collect::>().len(), names.len(), "{names:?}"); + assert_eq!(text.matches("%AI3_BeginPattern: (Dots)").count(), 1); +} + +/// A gradient paint is matched with the definitions of the same gradient, not with each +/// definition: 1,000 gradients of their own and 1,000 paints of 10 others take a few comparisons +/// each, where comparing each definition in turn takes hundreds of thousands. +#[test] +fn gradient_definitions_are_found_without_comparing_each() { + let doc = many_gradients(1000, 1000, 10, 0); + let comparisons = |scanned: bool| { + writer::GRADIENT_COMPARISONS.with(|c| c.set(0)); + program_scanned(&doc, scanned); + writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get) + }; + let (indexed, scanned) = (comparisons(false), comparisons(true)); + assert!(indexed <= 2 * 2010, "{indexed} comparisons through the index"); + assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index"); +} + +/// The time to write 5,000 rectangles with gradients of their own, 5,000 with 50 others and 20 +/// gradient swatches, with the definitions found by comparing each in turn and through their +/// indexes: the median of 7 runs of each, alternating, with the programs compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture gradient_definitions_timing`. +#[test] +#[ignore = "timing"] +fn gradient_definitions_timing() { + let doc = many_gradients(5000, 5000, 50, 20); + let mut times = [vec![], vec![]]; + let mut programs: [Option>; 2] = [None, None]; + let mut how = ""; + for _ in 0..7 { + for (k, scanned) in [true, false].into_iter().enumerate() { + let (start, h) = thread_time(); + let program = program_scanned(&doc, scanned); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + programs[k].get_or_insert(program); + } + } + assert_eq!(programs[0], programs[1]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("median of 7 runs ({how}):"); + println!("| definitions found | median (ms) | runs (ms) |"); + println!("|---|---:|---|"); + for (k, label) in ["by comparing each", "through the indexes"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect(); + println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", ")); + } +} + /// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop, /// and reads back with each stop on its side. #[test] @@ -4197,6 +4324,165 @@ fn images_that_cant_be_decoded_are_mid_gray_boxes() { assert_eq!(paint(n.appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); } +/// A `w` × `h` RGB image whose pixels follow from `seed`, no two of its pixels gray. +fn seeded_png(seed: u32, (w, h): (u32, u32)) -> Vec { + let px = |x: u32, y: u32| { + let v = (x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663) ^ seed.wrapping_mul(83_492_791)).to_le_bytes(); + image::Rgb([v[0], v[1] | 1, v[2] & 0xfe]) + }; + png_of(image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, px))) +} + +/// A document placing `blobs` in turn on one layer, each `times` times: the first, the second and +/// so on, then the first again. Each blob is kept under `keys`' key at its index. +fn images_in_turn(blobs: &[ImageBlob], keys: &[&str], times: usize) -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for (blob, key) in blobs.iter().zip(keys) { + doc.images.insert((*key).to_string(), blob.clone()); + } + for i in 0..times * blobs.len() { + let key = keys[i % blobs.len()].to_string(); + let xf = Affine::translate((f64::from(u32::try_from(i).unwrap()), 10.0)) * Affine::scale(2.0); + let im = ImageObject { key, width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None }; + let node = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + } + doc +} + +/// `doc` written keeping the pixels of each image read (`last_only` false) or of the image read +/// last alone, and how many times an image's pixels were read. +fn export_reading(doc: &Document, last_only: bool) -> (AiEditingOutput, usize) { + writer::LAST_SAMPLES_ONLY.with(|l| l.set(last_only)); + writer::SAMPLE_READS.with(|n| n.set(0)); + let out = export_ai_editing(doc, &opts()); + writer::LAST_SAMPLES_ONLY.with(|l| l.set(false)); + (out.unwrap(), writer::SAMPLE_READS.with(std::cell::Cell::get)) +} + +/// `doc` written both ways ([`export_reading`]), the files and warnings compared whole, and the +/// reads of each way. +fn reads_for_the_same_file(doc: &Document) -> (usize, usize) { + let (kept, kept_reads) = export_reading(doc, false); + let (last, last_reads) = export_reading(doc, true); + assert!(kept.program == last.program, "the files differ"); + assert_eq!(kept.header, last.header); + assert_eq!(kept.warnings, last.warnings); + (kept_reads, last_reads) +} + +/// Two images placed one after the other 25 times each are each read once in a save, and the file +/// is the same as when only the image read last is kept. +#[test] +fn images_placed_in_turn_are_read_once_a_save() { + // GUARDS: each image was read again whenever the other was placed between its copies. + let blobs = [ImageBlob::png(seeded_png(1, (4, 4))), ImageBlob::png(seeded_png(2, (4, 4)))]; + let doc = images_in_turn(&blobs, &["a", "b"], 25); + assert_eq!(reads_for_the_same_file(&doc), (2, 50)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 50); +} + +/// A document of one image placed many times reads it once, and one without images reads none. +#[test] +fn one_image_is_read_once_and_no_image_never() { + let doc = images_in_turn(&[ImageBlob::png(seeded_png(3, (4, 4)))], &["a"], 10); + assert_eq!(reads_for_the_same_file(&doc), (1, 1)); + assert_eq!(reads_for_the_same_file(&Document::new(200.0, 100.0)), (0, 0)); +} + +/// An image that can't be read, placed between copies of another, is read once too, and each copy +/// is still its gray outline with the same warning. +#[test] +fn an_image_that_cant_be_read_is_read_once_a_save() { + // GUARDS: an image that can't be read was read again whenever another image came between. + let blobs = [ImageBlob::png(b"not an image".to_vec()), ImageBlob::png(seeded_png(4, (4, 4)))]; + let doc = images_in_turn(&blobs, &["bad", "good"], 3); + assert_eq!(reads_for_the_same_file(&doc), (2, 6)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGES]); + assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 3); +} + +/// The same data under two MIME types is two images: each is read once, apart from the other. +#[test] +fn the_same_data_of_another_type_is_read_apart() { + let png = ImageBlob::png(seeded_png(5, (4, 4))); + let other = ImageBlob { mime: "image/x-other".into(), ..png.clone() }; + assert!(Arc::ptr_eq(&png.bytes, &other.bytes)); + let doc = images_in_turn(&[png, other], &["png", "other"], 3); + assert_eq!(reads_for_the_same_file(&doc), (2, 6)); +} + +/// Past the limits on the samples kept (bytes and images), an image is kept beside them in place +/// of the one before it, and the others are read again where they come: what is kept stays within +/// both limits, and the file is the same. +#[test] +fn images_past_the_limits_are_read_again_and_written_the_same() { + // Images of 48, 75 and 108 bytes of samples, then two of 48: 123 bytes and two images fit. + let sizes = [(4, 4), (5, 5), (6, 6), (4, 4), (4, 4)]; + let blobs: Vec<_> = (0u32..).zip(sizes).map(|(i, s)| ImageBlob::png(seeded_png(10 + i, s))).collect(); + let doc = images_in_turn(&blobs, &["a", "b", "c", "d", "e"], 3); + for (limits, kept_most, reads) in [((130, 8), (123, 2), 2 + 3 * 3), ((10_000, 3), (48 + 75 + 108, 3), 3 + 2 * 3)] { + writer::SAMPLE_LIMITS.with(|l| l.set(limits)); + writer::SAMPLES_KEPT.with(|k| k.set((0, 0, false))); + let (kept_reads, last_reads) = reads_for_the_same_file(&doc); + let (bytes, images, beside) = writer::SAMPLES_KEPT.with(std::cell::Cell::get); + writer::SAMPLE_LIMITS.with(|l| l.set((256 << 20, 256))); + assert!(bytes <= limits.0 && images <= limits.1, "{limits:?}: kept {bytes} bytes of {images} images"); + assert_eq!((bytes, images, beside), (kept_most.0, kept_most.1, true), "{limits:?}"); + assert_eq!((kept_reads, last_reads), (reads, 15), "{limits:?}"); + } +} + +/// The time this thread has run, and how it was measured. +fn thread_time() -> (std::time::Duration, &'static str) { + if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + return (std::time::Duration::from_nanos(ns), "thread CPU time"); + } + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + (START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time") +} + +/// The time to write two 2048 × 2048 images placed one after the other 25 times each, keeping the +/// pixels of each image read and of the image read last alone: the median of 7 runs of each, +/// alternating, with the files compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture images_placed_in_turn_are_written_quickly`. +#[test] +#[ignore = "timing"] +fn images_placed_in_turn_are_written_quickly() { + let blobs = [ImageBlob::png(seeded_png(1, (2048, 2048))), ImageBlob::png(seeded_png(2, (2048, 2048)))]; + let doc = images_in_turn(&blobs, &["a", "b"], 25); + let mut times = [vec![], vec![]]; + let mut files: [Option>; 2] = [None, None]; + let mut reads = [0, 0]; + let mut how = ""; + for _ in 0..7 { + for (k, last_only) in [false, true].into_iter().enumerate() { + let (start, h) = thread_time(); + let (out, n) = export_reading(&doc, last_only); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + reads[k] = n; + files[k].get_or_insert(out.program); + } + } + assert!(files[0] == files[1], "the files differ"); + assert_eq!(reads, [2, 50]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("50 placements of two 2048 x 2048 images, median of 7 runs ({how}):"); + println!("| pixels kept | images read | median (ms) | runs (ms) |"); + println!("|---|---:|---:|---|"); + for (k, label) in ["each image read", "the image read last"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.0}", ms(*d))).collect(); + println!("| {label} | {} | {:.0} | {} |", reads[k], ms(times[k][3]), runs.join(", ")); + } +} + #[test] fn sixteen_bit_images_are_written_at_eight_bits() { let mut doc = Document::new(200.0, 100.0); @@ -7181,6 +7467,166 @@ fn art_styles_are_written_in_their_forms() { assert!(!two.contains("%AI9_BeginArtStyleList"), "{two}"); } +/// A document with `k` of each object a save checks a style on, on rows 20 pt apart: objects linked +/// to a new document's graphic style and to one of the document's own, objects with the same drop +/// shadow, two objects with different gradients under a drop shadow on the same outline, and paths +/// with a Calligraphic brush and a drop shadow. +fn checked_styles_document(k: usize) -> Document { + let mut doc = Document::new(400.0, 20.0 * k as f64 + 20.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + let lit_ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(solid(Color::rgb(0.2, 0.5, 0.9)), solid(Color::BLACK), 1.0) }; + let mut lit = vectorcraft_doc::GraphicStyle::new("Lit", lit_ap); + lit.id = 40; + doc.graphic_styles.push(lit); + let ramp = |c: Color| { + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, c)]; + Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Linear, stops, ..Gradient::default() }))) + }; + for i in 0..k { + let y = 10.0 + 20.0 * i as f64; + for (x, name) in [(10.0, "Sunshine"), (60.0, "Lit")] { + let g = doc.graphic_style(name).unwrap().clone(); + let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 15.0)), ap); + n.extras_mut().graphic_style = Some(g.id); + put(&mut doc, n); + } + let n = styled_rect(&mut doc, "Shadowed", Rect::new(110.0, y, 150.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![drop_shadow()]); + put(&mut doc, n); + for c in [Color::BLACK, Color::rgb(0.9, 0.2, 0.1)] { + let n = styled_rect(&mut doc, "Graded", Rect::new(160.0, y, 200.0, y + 15.0), ramp(c), Paint::None, vec![drop_shadow()]); + put(&mut doc, n); + } + let stroke = Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 2.0); + let mut line = Node::path(doc.alloc_id(), shapes::line((210.0, y).into(), (380.0, y + 10.0).into()), stroke); + line.appearance.stroke_mut().unwrap().brush = Some("Nib".into()); + line.appearance.effects = vec![drop_shadow()]; + put(&mut doc, line); + } + doc +} + +/// A save parses each style text once, however many objects it checks with it: the panel's styles, +/// objects linked to them, objects with the same style of their own and brushed paths. Each object +/// is still checked: every linked object keeps its link, each graded object reads back with its own +/// gradient, and each brushed path with its brush. +#[test] +fn a_save_parses_each_style_text_once() { + let parses = |doc: &Document| { + crate::import::ART_STYLE_PARSES.set(0); + let out = export_ai_editing(doc, &opts()).unwrap(); + (crate::import::ART_STYLE_PARSES.get(), String::from_utf8(out.program).unwrap().replace("\r\n", "\n")) + }; + let (one, _) = parses(&checked_styles_document(1)); + let doc = checked_styles_document(4); + let (four, p) = parses(&doc); + assert!(one > 0); + assert_eq!(four, one, "parses with one of each object and with four"); + for linked in ["1 (Sunshine) XW\n", "1 (Lit) XW\n"] { + assert_eq!(p.matches(linked).count(), 4, "{linked}"); + } + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + let paints: Vec<&Paint> = + kids.iter().filter(|n| n.name.as_deref() == Some("Graded")).filter_map(|n| n.appearance.fill().map(|f| &f.paint)).collect(); + let graded: Vec<&Paint> = doc.layers[0] + .children() + .unwrap() + .iter() + .filter(|n| n.name.as_deref() == Some("Graded")) + .map(|n| &n.appearance.fill().unwrap().paint) + .collect(); + assert_eq!(paints.len(), 8); + for (got, want) in paints.iter().zip(&graded) { + let (Paint::Gradient(got), Paint::Gradient(want)) = (got, want) else { panic!("a gradient fill: {got:?}") }; + assert_eq!(got.gradient.stops, want.gradient.stops); + } + let brushed: Vec<&Arc> = kids.iter().filter(|n| n.appearance.stroke().and_then(|s| s.brush.as_deref()) == Some("Nib")).collect(); + assert_eq!(brushed.len(), 4); + assert!(brushed.iter().all(|n| n.appearance.effects.len() == 1 && matches!(n.kind, NodeKind::Path { .. }))); +} + +/// A save that keeps each style text's parse writes the same program, header, warnings and private +/// data as one that parses the text again at every check. +#[test] +fn a_save_writes_the_same_with_each_style_text_parsed_once() { + let save = |doc: &Document, reparse: bool| { + writer::REPARSE.set(reparse); + let out = export_ai_editing(doc, &opts()).unwrap(); + let private = private_data(doc, &opts()).unwrap(); + writer::REPARSE.set(false); + (out.program, out.header, out.warnings, private.0.data, private.1) + }; + for doc in [styles_document(), checked_styles_document(4), brushes_document()] { + let (once, again) = (save(&doc, false), save(&doc, true)); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); + } +} + +/// The CPU time of saving a document with 40 graphic styles, 20,000 rectangles linked to them in +/// turn and 5,000 paths with an Outer Glow of their own in 20 settings, with each style text's parse +/// kept and with the text parsed again at every check: the median of 7 runs of each, alternating. +/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture style_parse_time`. +#[test] +#[ignore = "timing; run by hand"] +fn style_parse_time() { + let mut doc = Document::new(2000.0, 2000.0); + let mut ids = vec![]; + for i in 0..40u32 { + let shade = i as f32 / 40.0; + let mut ap = Appearance::basic(solid(Color::rgb(shade, 0.4, 1.0 - shade)), solid(Color::BLACK), 1.0 + f64::from(i % 4)); + let round = fx("stylize.roundCorners", serde_json::json!({"radius": 2.0 + f64::from(i % 5)})); + ap.effects = vec![fx("stylize.dropShadow", serde_json::json!({"x": f64::from(i % 7), "y": 4.0})), round]; + let mut g = vectorcraft_doc::GraphicStyle::new(format!("Style {i}"), ap); + g.id = 100 + i; + ids.push(g.id); + doc.graphic_styles.push(g); + } + for i in 0..20_000usize { + let g = doc.graphic_style_by_id(ids[i % ids.len()]).unwrap().clone(); + let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), ap); + n.extras_mut().graphic_style = Some(g.id); + put(&mut doc, n); + } + for i in 0..5_000usize { + let glow = fx("stylize.outerGlow", serde_json::json!({"blur": 1.0 + (i % 20) as f64})); + let (x, y) = ((i % 100) as f64 * 20.0, 1000.0 + (i / 100) as f64 * 20.0); + let n = styled_rect(&mut doc, "Glow", Rect::new(x, y, x + 15.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![glow]); + put(&mut doc, n); + } + // The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock. + let start = std::time::Instant::now(); + let cpu = || { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::().ok())) + .unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) + }; + let mut times: [Vec; 2] = [vec![], vec![]]; + let mut parses = [0, 0]; + let mut outputs: [Vec; 2] = [vec![], vec![]]; + for _ in 0..7 { + for (k, reparse) in [(0, true), (1, false)] { + writer::REPARSE.set(reparse); + crate::import::ART_STYLE_PARSES.set(0); + let t = cpu(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + times[k].push(cpu() - t); + parses[k] = crate::import::ART_STYLE_PARSES.get(); + outputs[k] = out.program; + } + } + writer::REPARSE.set(false); + assert!(outputs[0] == outputs[1]); + for (k, label) in [(0, "parsed at every check"), (1, "parsed once")] { + times[k].sort_unstable(); + let ms: Vec = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect(); + println!("{label}: median {:.1} ms CPU, {} parses, runs {}", times[k][3] as f64 / 1e6, parses[k], ms.join(" ")); + } +} + /// Objects whose appearance the reader wouldn't read with their style are written as their /// drawn look, with the warnings they were written with before; graphic styles it wouldn't read /// are left out with a warning; and a document without effects or styles of its own has no art @@ -9758,6 +10204,7 @@ fn brush_library() -> Vec { rotation: (-45.0, 30.0), rotation_relative_to_path: true, colorization: Colorization::Tints, + hue_jitter: 0.0, modes: Some([Variation::Random, Variation::Fixed, Variation::Pressure, Variation::Random]), }), }, @@ -9864,6 +10311,22 @@ fn brushes_are_read_back_with_their_settings() { } } +/// The writer does not write a Scatter brush's hue jitter: the brush would open without it, so it +/// is left out of the Brushes panel and reported. +#[test] +fn a_scatter_brush_with_hue_jitter_is_left_out() { + use vectorcraft_brush::BrushKind; + let mut lib = brush_library(); + let BrushKind::Scatter(s) = &mut lib[1].kind else { panic!("scatter") }; + s.hue_jitter = 60.0; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = vectorcraft_brush::library(&read_back(&doc)); + assert_eq!(back.iter().map(|b| b.name.as_str()).collect::>(), ["Nib", "Ribbon", "Plain ribbon"]); +} + /// An Art brush's options, without its art. #[derive(Debug, PartialEq)] struct ArtBrushOptions(serde_json::Value); @@ -10193,6 +10656,7 @@ fn more_brush_settings_are_read_back() { rotation: (15.0, 15.0), rotation_relative_to_path: false, colorization: Colorization::None, + hue_jitter: 0.0, modes: Some([Variation::Tilt, Variation::Bearing, Variation::Fixed, Variation::Rotation]), }; let lib = vec![ @@ -10255,6 +10719,40 @@ fn brush_art_of_a_straight_line_comes_back_as_the_line() { } } +/// A Scatter brush's art is written turned over into its section (y up), so the side that is down the +/// page in the brush's copies is up in the section: a triangle with its point down comes out with +/// its point above its base, and comes back with its point down. +#[test] +fn a_scatter_brushs_art_is_written_turned_over() { + use vectorcraft_brush::{Brush, BrushKind, Scatter}; + use vectorcraft_geom::{Point, SubPath}; + let point_down = PathData { subpaths: vec![SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(20.0, 10.0)], true)] }; + let art = Node::path(vectorcraft_doc::NodeId(1), point_down, Appearance::basic(black_fill(), Paint::None, 0.0)); + let lib = vec![Brush { name: "Wedge".into(), kind: BrushKind::Scatter(Scatter { art, ..Scatter::default() }) }]; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let text = program(&doc); + let start = text.find("%AI8_BeginBrushPattern").unwrap(); + let end = start + text[start..].find("%AI8_EndBrushPattern").unwrap(); + // The points of the frame and the triangle: the triangle's point is the one between the + // frame's left and right edges. + let points: Vec<(f64, f64)> = text[start..end] + .lines() + .filter_map(|l| l.strip_suffix(" m").or_else(|| l.strip_suffix(" L"))) + .filter_map(|l| { + let mut n = l.split_whitespace().map(|v| v.parse::().ok()); + Some((n.next()??, n.next()??)) + }) + .collect(); + let (left, right) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, r), p| (l.min(p.0), r.max(p.0))); + let bottom = points.iter().map(|p| p.1).fold(f64::INFINITY, f64::min); + let tip: Vec = points.iter().filter(|p| p.0 > left + 1e-3 && p.0 < right - 1e-3).map(|p| p.1).collect(); + assert!(!tip.is_empty() && tip.iter().all(|y| (y - bottom - 10.0).abs() < 1e-3), "the point is 10 above the base in the section: {points:?}"); + let back = vectorcraft_brush::library(&read_back(&doc)); + let (BrushKind::Scatter(got), BrushKind::Scatter(want)) = (&back[0].kind, &lib[0].kind) else { panic!("{back:?}") }; + assert!(same_tree(&art_tree(&got.art), &art_tree(&want.art)), "{:#?}", got.art); +} + /// Brush art of a path with several subpaths is written as a compound path, which the reader reads as /// a compound path of one path for each subpath, and is weighed as the reader weighs that against the /// art it copies into one file's brushes: of two Art brushes whose art is a path of 30,000 squares, @@ -11041,6 +11539,192 @@ fn variable_font_instances_name_their_design_space() { ); } +/// Style 12 pt black in family `family` and style `style`, with the Variable Font settings `axes`. +fn font_style(family: &str, style: &str, axes: &[(&str, f64)]) -> vectorcraft_doc::CharStyle { + vectorcraft_doc::CharStyle { + font_family: family.into(), + font_style: style.into(), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..style_of(12.0) + } +} + +/// A document of `k` rows 30 pt apart, each with point type in three runs (Source Sans 3 Regular +/// and Bold, and the variable test font's Bold at a weight of 650), point type in four (Inter +/// Medium, the variable test font's Bold at 500 and at a weight that differs from 500 by less than +/// the font record's precision, and a family that isn't installed), and area type threaded through +/// two frames in Bold and the variable test font's Regular. +fn fonted_document(k: usize) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + use vectorcraft_geom::Point; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let (regular, bold) = (style_of(12.0), font_style("Source Sans 3", "Bold", &[])); + let mut doc = Document::new(400.0, 30.0 * k as f64 + 30.0); + let layer = doc.layers[0].id; + for i in 0..k { + let y = 20.0 + 30.0 * i as f64; + let mut three = TextObject::point(Point::new(10.0, y), "", regular.clone()); + three.runs = vec![ + TextRun::new("One ", regular.clone()), + TextRun::new("two ", bold.clone()), + TextRun::new("three", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)])), + ]; + let mut four = TextObject::point(Point::new(100.0, y), "", regular.clone()); + four.runs = vec![ + TextRun::new("four ", font_style("Inter", "Medium", &[])), + TextRun::new("five ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.0)])), + TextRun::new("six ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.000_001)])), + TextRun::new("seven", font_style("No Such Family", "Bold", &[])), + ]; + let mut first = TextObject::point(Point::ZERO, "", bold.clone()); + first.runs = vec![TextRun::new("eight nine ", bold.clone()), TextRun::new("ten", font_style(VARIABLE_FAMILY, "Regular", &[]))]; + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(250.0, y - 10.0, 315.0, y + 10.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs = vec![TextRun::new("", bold.clone())]; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(325.0, y - 10.0, 390.0, y + 10.0)) }; + let nodes = [text_node(&mut doc, three), text_node(&mut doc, four), text_node(&mut doc, first), text_node(&mut doc, second)]; + doc.text_threads.push(vec![nodes[2].id, nodes[3].id]); + for n in nodes { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + } + doc +} + +/// A save resolves the font of each style once, however many runs are set in it: as many fonts are +/// resolved (font records and checks that a font comes back) for one row of type as for four. Two +/// weights of a variable font that the font record writes as one number are one font written. +#[test] +fn a_save_resolves_each_font_once() { + // How many fonts a save of `doc` resolves, in a save during which the font database didn't change. + let resolves = |doc: &Document| { + let db = vectorcraft_text::FontDb::global(); + for _ in 0..20 { + let before = db.generation(); + writer::FONT_RESOLVES.set(0); + export_ai_editing(doc, &opts()).unwrap(); + if db.generation() == before { + return writer::FONT_RESOLVES.get(); + } + } + panic!("the font database changed during every save"); + }; + let one = resolves(&fonted_document(1)); + let doc = fonted_document(4); + let four = resolves(&doc); + assert!(one > 0); + assert_eq!(four, one, "fonts resolved with one row of type and with four"); + let td = text_document(&program(&doc)); + // 650 × 65536 and 500 × 65536. + assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 42598400 ]").count(), 1, "{td}"); + assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 32768000 ]").count(), 1, "{td}"); + assert_eq!(td.matches("/CoolTypeFont").count(), 8, "seven fonts and the hidden characters' font: {td}"); +} + +/// A save that resolves each style's font once writes the same program, header, warnings and private +/// data as one that resolves the font of every run again: with type in many fonts, threaded type, +/// type in envelopes, and type taken out again when an envelope is written as its art. +#[test] +fn a_save_writes_the_same_with_each_font_resolved_once() { + use vectorcraft_doc::live::EnvelopeKind; + let save = |doc: &Document, each_run: bool| { + writer::RESOLVE_EACH_RUN.set(each_run); + let out = export_ai_editing(doc, &opts()).unwrap(); + let private = private_data(doc, &opts()).unwrap(); + writer::RESOLVE_EACH_RUN.set(false); + (out.program, out.header, out.warnings, private.0.data, private.1) + }; + let mut docs = vec![sample(), typed(), fonted_document(3)]; + for (_, kind) in live_envelope_kinds() { + for editing in [false, true] { + let mut doc = Document::new(200.0, 100.0); + let envelope = typed_envelope_node(&mut doc, kind.clone(), editing); + docs.push(alone(envelope)); + } + } + for doc in &docs { + let (once, again) = (save(doc, false), save(doc, true)); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); + } + // An envelope of type one object short of room: it is written as its art, and its story and fonts + // are taken out again. + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut doc = Document::new(200.0, 100.0); + let envelope = typed_envelope_node(&mut doc, kind, false); + let doc = alone(envelope); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let within = |each_run: bool| { + writer::RESOLVE_EACH_RUN.set(each_run); + let out = export_within(&doc, &opts(), read - 1).unwrap(); + writer::RESOLVE_EACH_RUN.set(false); + (out.program, out.warnings) + }; + let (once, again) = (within(false), within(true)); + assert!(once.1.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", once.1); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); +} + +/// The CPU time of saving a document of 10,000 point type objects, each in three runs drawn in turn +/// from four fonts (Source Sans 3 Regular and Bold, Inter Medium, and the variable test font's Bold +/// at a weight of 650), with each style's font resolved once and with the font of every run +/// resolved again: the median of 7 runs of each, alternating. +/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture font_resolve_time`. +#[test] +#[ignore = "timing; run by hand"] +fn font_resolve_time() { + use vectorcraft_doc::{TextObject, TextRun}; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let fonts = [ + style_of(12.0), + font_style("Source Sans 3", "Bold", &[]), + font_style("Inter", "Medium", &[]), + font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)]), + ]; + let mut doc = Document::new(2000.0, 2000.0); + let layer = doc.layers[0].id; + for i in 0..10_000usize { + let (x, y) = ((i % 100) as f64 * 20.0, (i / 100) as f64 * 20.0 + 10.0); + let mut t = TextObject::point(vectorcraft_geom::Point::new(x, y), "", fonts[0].clone()); + t.runs = (0..3).map(|r| TextRun::new(["ab ", "cd ", "ef"][r], fonts[(i + r) % fonts.len()].clone())).collect(); + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + // The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock. + let start = std::time::Instant::now(); + let cpu = || { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::().ok())) + .unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) + }; + // A first save loads the faces the document names. + export_ai_editing(&doc, &opts()).unwrap(); + let mut times: [Vec; 2] = [vec![], vec![]]; + let mut resolves = [0, 0]; + let mut outputs: [Vec; 2] = [vec![], vec![]]; + for _ in 0..7 { + for (k, each_run) in [(0, true), (1, false)] { + writer::RESOLVE_EACH_RUN.set(each_run); + writer::FONT_RESOLVES.set(0); + let t = cpu(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + times[k].push(cpu() - t); + resolves[k] = writer::FONT_RESOLVES.get(); + outputs[k] = out.program; + } + } + writer::RESOLVE_EACH_RUN.set(false); + assert!(outputs[0] == outputs[1]); + for (k, label) in [(0, "resolved for every run"), (1, "resolved once")] { + times[k].sort_unstable(); + let ms: Vec = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect(); + println!("{label}: median {:.1} ms CPU, {} fonts resolved, runs {}", times[k][3] as f64 / 1e6, resolves[k], ms.join(" ")); + } +} + fn style_of(size: f64) -> vectorcraft_doc::CharStyle { style(size, Color::BLACK) } diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index f268bcbaf6..41254840cb 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -37,20 +37,21 @@ pub(super) use envelopes::ENVELOPES; pub(super) use meshes::MESHES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects}; #[cfg(test)] -pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; +pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, REPARSE, STYLE_LINKS, WARPED_IMAGES, same_appearance}; pub(super) use texts::wraps_held; pub(super) use images::PAYLOAD; #[cfg(test)] -pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; +pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT}; #[cfg(test)] pub(super) use paints::{ - GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name, + GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS, + SWATCH_PLACEMENT, free_gradient_name, }; #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] -pub(super) use texts::TYPE_ATTRIBUTES; +pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; @@ -200,11 +201,11 @@ pub(super) struct Writer<'a> { /// pattern's definition, the pattern's space turned y up. canvas: Affine, /// The gradient definitions, in the order they are first used. - gradients: Vec, + gradients: paints::GradientDefs, /// The number the next new gradient definition's name tries first (1 is `Gradient`). next_gradient: u64, /// The pattern definitions written, each after those its art uses. - patterns: Vec, + patterns: paints::PatternDefs, /// The patterns whose definitions are being written. defining: Vec, /// Writing the palette: the definitions it adds are for its swatches only. @@ -320,9 +321,9 @@ pub(super) struct Writer<'a> { /// How many more envelopes and images with a Warp may be written live: as many as the reader /// checks in one file ([`crate::import::ENVELOPE_CHECKS`]), which it spends on both. checks_left: usize, - /// The image read last and its pixels ([`images::Samples::of`], `None` when they can't be - /// read): the pieces of a warped image, which follow one another, read them once. - last_samples: Option<(vectorcraft_doc::ImageBlob, Option)>, + /// The images read so far and their pixels: an image placed again, and each piece of a warped + /// image, is read once. + read_samples: images::SampleCache, /// The images written whole so far, by the address of their data (which each entry keeps), each /// with the index of its samples in [`Self::payloads`]. whole_images: HashMap>, usize)>, @@ -357,9 +358,9 @@ impl<'a> Writer<'a> { grad_space: to_art, tile_grad_space: Affine::translate((-origin.0, origin.1)), canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art, - gradients: vec![], + gradients: paints::GradientDefs::default(), next_gradient: 1, - patterns: vec![], + patterns: paints::PatternDefs::default(), defining: vec![], in_palette: false, canvas_origin: origin, @@ -422,7 +423,7 @@ impl<'a> Writer<'a> { definition_links: 0, definition_symbol_nodes: 0, max_objects: crate::import::MAX_EDITING_OBJECTS, - last_samples: None, + read_samples: images::SampleCache::default(), whole_images: HashMap::new(), shown: vec![], windowed: None, @@ -1604,7 +1605,7 @@ impl<'a> Writer<'a> { let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); placed.map(|p| (p, self.texts.take_lost())) } else { - self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t))) + self.texts.add(t, self.canvas).map(|story| ((story, 0), self.texts.loses(t))) }; let Some(((story, frame), lost)) = placed else { // The text document can't hold it: the outlines count their own objects. diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index 986d60ef9c..ac7ca48ac8 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -401,11 +401,12 @@ impl Writer<'_> { fn brush_out(&mut self, b: &Brush) -> Option { let plugin = crate::import::brush_plugin_name(&b.kind); let section = format!("Brush Art {}", self.brush_set.sections + 1); - // The art as the reader reads it: a section is read with y down, and an Art brush's art is - // turned over after that (its section's y up is the right of the path). + // The art as the reader reads it: a section is read with y down, and a Scatter or Art + // brush's art is turned over after that (its section's y up is down the page in each + // Scatter copy and the right of the path in Art). let (params, art) = match &b.kind { BrushKind::Calligraphic(c) => (calligraphic_params(c), None), - BrushKind::Scatter(s) => (scatter_params(s, §ion)?, Some((s.art.clone(), Affine::FLIP_Y))), + BrushKind::Scatter(s) => (scatter_params(s, §ion)?, Some((s.art.clone(), Affine::IDENTITY))), BrushKind::Art(a) => (art_params(a, §ion)?, Some((a.art.clone(), Affine::IDENTITY))), BrushKind::Pattern(_) | BrushKind::Bristle(_) => return None, }; @@ -565,14 +566,14 @@ impl Writer<'_> { /// Does the reader read the brushed strokes of style text `text` with their brushes on them? pub(super) fn brushed_style_reads(&mut self, text: &str) -> bool { self.brush_set(); - let section = super::styles::known_style("x", text); + let Some(parsed) = self.styles.parsed.get(text) else { return false }; let written = &self.brush_set.written; let read = self.brush_set.read.get_or_insert_with(|| { let brushes: Vec<(&str, &str, &str, Option<&Node>)> = written.iter().map(|b| (b.plugin, b.brush.name.as_str(), b.params.as_str(), b.art.as_ref())).collect(); crate::import::BrushesRead::new(&brushes) }); - read.style_reads(section.as_bytes(), "x") + read.style_reads(parsed) } /// The brushes' art in a non-printing block, then the brush manager's order and the brushes in diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs index 3813deccf9..408827663f 100644 --- a/crates/eps/src/ai_editing/writer/images.rs +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -1,6 +1,9 @@ //! Images: embedded ones as a raster with its samples, linked ones as a placed file with a preview //! (see [`crate::ai_editing`] for the form). +#[cfg(test)] +use std::cell::Cell; +use std::collections::HashMap; use std::fmt::Write; use std::sync::Arc; @@ -30,6 +33,87 @@ pub(super) const SAMPLES_LINE: &str = "XI\u{1}"; /// An image's pixels as the data holds them, and whether it had 16 bits a channel ([`Samples::of`]). pub(super) type Read = Arc<(Samples, bool)>; +/// The most bytes of samples a save keeps read ([`SampleCache`]): color and alpha together. +const KEPT_SAMPLE_BYTES: usize = 256 << 20; +/// The most images whose samples a save keeps read ([`SampleCache`]), those that can't be read +/// included. +const KEPT_IMAGES: usize = 256; + +#[cfg(test)] +thread_local! { + /// How many times [`Samples::of`] has read an image on this thread. + pub(in crate::ai_editing) static SAMPLE_READS: Cell = const { Cell::new(0) }; + /// Whether [`Writer::samples`] keeps only the image read last on this thread, to compare its + /// file with the one [`SampleCache`] gives. + pub(in crate::ai_editing) static LAST_SAMPLES_ONLY: Cell = const { Cell::new(false) }; + /// The bytes of samples and the images [`SampleCache`] keeps at most on this thread. + pub(in crate::ai_editing) static SAMPLE_LIMITS: Cell<(usize, usize)> = const { Cell::new((KEPT_SAMPLE_BYTES, KEPT_IMAGES)) }; + /// The most bytes of samples and images a [`SampleCache`] kept on this thread, and whether one + /// held an image beside them. + pub(in crate::ai_editing) static SAMPLES_KEPT: Cell<(usize, usize, bool)> = const { Cell::new((0, 0, false)) }; +} + +/// The bytes of samples and the images [`SampleCache`] keeps at most. +#[cfg(not(test))] +const fn sample_limits() -> (usize, usize) { + (KEPT_SAMPLE_BYTES, KEPT_IMAGES) +} + +#[cfg(test)] +fn sample_limits() -> (usize, usize) { + SAMPLE_LIMITS.with(Cell::get) +} + +/// The images read during a save and their pixels ([`Samples::of`], `None` when they can't be +/// read), so that an image placed again is read once: up to [`KEPT_IMAGES`] images and +/// [`KEPT_SAMPLE_BYTES`] of samples, and beside them the image read last that they have no room +/// for. An image is known by the address of its data and its MIME type; each entry keeps the +/// image, so no other data takes that address while the entry is kept. +#[derive(Default)] +pub(super) struct SampleCache { + /// By the address of the image's data, each image with that data and its pixels. + kept: HashMap)>>, + /// How many images `kept` holds. + images: usize, + /// The bytes of samples `kept` holds. + bytes: usize, + /// The image read last that `kept` had no room for, and its pixels. + last: Option<(ImageBlob, Option)>, +} + +/// Whether `a` is the image `b`: the same data and MIME type. +fn same_image(a: &ImageBlob, b: &ImageBlob) -> bool { + Arc::ptr_eq(&a.bytes, &b.bytes) && a.mime == b.mime +} + +impl SampleCache { + /// The pixels kept for `blob`, when it was read. + fn get(&self, blob: &ImageBlob) -> Option> { + let kept = self.kept.get(&(Arc::as_ptr(&blob.bytes) as usize)).and_then(|v| v.iter().find(|(b, _)| same_image(b, blob))); + kept.or(self.last.as_ref().filter(|(b, _)| same_image(b, blob))).map(|(_, read)| read.clone()) + } + + /// Keep `read`, the pixels of `blob`: with the others while both limits allow, else beside them + /// in place of the image read last. + fn keep(&mut self, blob: &ImageBlob, read: Option) { + let size = read.as_deref().map_or(0, |(s, _)| s.color.len().saturating_add(s.alpha.as_ref().map_or(0, Vec::len))); + let (most_bytes, most_images) = sample_limits(); + match self.bytes.checked_add(size).filter(|b| *b <= most_bytes) { + Some(bytes) if self.images < most_images => { + self.bytes = bytes; + self.images += 1; + self.kept.entry(Arc::as_ptr(&blob.bytes) as usize).or_default().push((blob.clone(), read)); + } + _ => self.last = Some((blob.clone(), read)), + } + #[cfg(test)] + SAMPLES_KEPT.with(|k| { + let (b, n, last) = k.get(); + k.set((b.max(self.bytes), n.max(self.images), last || self.last.is_some())); + }); + } +} + /// A copy of an image written as the part of it that its regions show ([`Writer::image`]). pub(super) struct Windowed { /// Where its raster is in the body. @@ -61,6 +145,8 @@ impl Samples { /// or RGB samples, with an alpha channel when they need one. `None` when they can't be decoded or are more than /// [`MAX_PIXELS`]; the flag is set when the image had 16 bits a channel. fn of(blob: &ImageBlob) -> Option<(Samples, bool)> { + #[cfg(test)] + SAMPLE_READS.with(|n| n.set(n.get() + 1)); // The header's size is checked before the inks are decoded. if blob.is_cmyk() && blob.header_size().is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= MAX_PIXELS) @@ -301,17 +387,26 @@ impl Writer<'_> { ); } - /// The pixels of `blob` ([`Samples::of`]), read once for images that follow one another with - /// the same data. + /// The pixels of `blob` ([`Samples::of`]), read once in a save for each image the + /// [`SampleCache`] has room for. fn samples(&mut self, blob: &ImageBlob) -> Option { - if let Some((last, read)) = &self.last_samples - && Arc::ptr_eq(&last.bytes, &blob.bytes) - && last.mime == blob.mime - { - return read.clone(); + #[cfg(test)] + if LAST_SAMPLES_ONLY.with(Cell::get) { + if let Some((last, read)) = &self.read_samples.last + && Arc::ptr_eq(&last.bytes, &blob.bytes) + && last.mime == blob.mime + { + return read.clone(); + } + let read = Samples::of(blob).map(Arc::new); + self.read_samples.last = Some((blob.clone(), read.clone())); + return read; + } + if let Some(read) = self.read_samples.get(blob) { + return read; } let read = Samples::of(blob).map(Arc::new); - self.last_samples = Some((blob.clone(), read.clone())); + self.read_samples.keep(blob, read.clone()); read } diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index 1d5651b596..5a850d7db3 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -1,7 +1,9 @@ //! Gradients and patterns: their definitions in the setup, gradient instances on paths and the //! pattern operators (see [`crate::ai_editing`] for the form). +use std::collections::HashMap; use std::fmt::Write; +use std::hash::{Hash, Hasher}; use vectorcraft_color::gradient::GradientGeom; use vectorcraft_color::swatch::REGISTRATION; @@ -46,6 +48,134 @@ pub(super) struct PatternOut { used: bool, } +#[cfg(test)] +thread_local! { + /// Whether [`GradientDefs`] and [`PatternDefs`] find definitions on this thread by comparing + /// the gradient or name with each definition in turn. + pub(in crate::ai_editing) static SCANNED_DEFINITIONS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`GradientDefs::find`] has compared two gradients on this thread. + pub(in crate::ai_editing) static GRADIENT_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Are gradients `a` and `b` the same? +fn same_gradient(a: &Gradient, b: &Gradient) -> bool { + #[cfg(test)] + GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1)); + a == b +} + +/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its +/// bits, with -0 as 0); different gradients may share one. +fn gradient_key(g: &Gradient) -> u64 { + let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; + let mut h = std::hash::DefaultHasher::new(); + std::mem::discriminant(&g.kind).hash(&mut h); + std::mem::discriminant(&g.method).hash(&mut h); + (g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h); + for s in &g.stops { + let (model, c) = match s.color { + Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]), + Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), + Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), + Color::Lab { l, a, b } => (3, [l, a, b, 0.0]), + }; + (model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h); + (&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h); + } + h.finish() +} + +/// The gradient definitions, in the order they are first used, found by name and by gradient +/// without comparing each one. +#[derive(Default)] +pub(super) struct GradientDefs { + list: Vec, + /// Each definition's place in `list`, by its name (no two definitions share one). + names: HashMap, + /// The places in `list` of the definitions no swatch names, in order, by their gradient's key + /// ([`gradient_key`]). + ramps: HashMap>, +} + +impl GradientDefs { + /// Is `name` a definition's name? + fn has_name(&self, name: &str) -> bool { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.list.iter().any(|d| d.name == name); + } + self.names.contains_key(name) + } + + /// The place of the definition of `g`: the swatch `swatch` names when it is a gradient swatch + /// of the same gradient, else the first definition of the same gradient that no swatch names. + fn find(&self, g: &Gradient, swatch: Option<&str>) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return swatch + .and_then(|s| self.list.iter().position(|d| d.swatch && d.name == s && same_gradient(&d.gradient, g))) + .or_else(|| self.list.iter().position(|d| !d.swatch && same_gradient(&d.gradient, g))); + } + let held = |i: &usize, swatch: bool| self.list.get(*i).is_some_and(|d| d.swatch == swatch && same_gradient(&d.gradient, g)); + swatch + .and_then(|s| self.names.get(s).copied().filter(|i| held(i, true))) + .or_else(|| self.ramps.get(&gradient_key(g))?.iter().copied().find(|i| held(i, false))) + } + + /// Add `d`, whose name no definition has. + fn push(&mut self, d: GradientDef) { + let i = self.list.len(); + if !d.swatch { + self.ramps.entry(gradient_key(&d.gradient)).or_default().push(i); + } + self.names.insert(d.name.clone(), i); + self.list.push(d); + } + + /// Keep the first `len` definitions; the names of those removed are free again. + fn truncate(&mut self, len: usize) { + while self.list.len() > len { + let Some(d) = self.list.pop() else { break }; + self.names.remove(&d.name); + if !d.swatch { + // Places are added in order, so the removed definition's is the last of its key's. + let key = gradient_key(&d.gradient); + if let Some(places) = self.ramps.get_mut(&key) { + places.pop(); + if places.is_empty() { + self.ramps.remove(&key); + } + } + } + } + } +} + +/// The pattern definitions written, each after those its art uses, found by name. +#[derive(Default)] +pub(super) struct PatternDefs { + list: Vec, + /// Each definition's place in `list`, by its name (no two definitions share one). + names: HashMap, +} + +impl PatternDefs { + /// The place of pattern `name`'s definition. + fn find(&self, name: &str) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.list.iter().position(|p| p.name == name); + } + self.names.get(name).copied() + } + + /// Add `p`, whose name no definition has. + fn push(&mut self, p: PatternOut) { + self.names.insert(p.name.clone(), self.list.len()); + self.list.push(p); + } +} + pub(in crate::ai_editing) const DIAMOND: &str = "diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps"; pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps"; @@ -118,7 +248,7 @@ impl Writer<'_> { && let stops = curve_as_stops(&g.gradient) && let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS) && writable_gradient(&gradient) - && !self.gradients.iter().any(|d| d.name == sw.name) + && !self.gradients.has_name(&sw.name) { self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false }); } @@ -131,17 +261,14 @@ impl Writer<'_> { /// swatch or a pattern). fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String { let used = !self.in_palette; - let found = swatch - .and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g)) - .or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g)); - if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) { + let found = self.gradients.find(g, swatch); + if let Some(d) = found.and_then(|i| self.gradients.list.get_mut(i)) { d.used |= used; return d.name.clone(); } let (doc, gradients) = (self.doc, &self.gradients); - let name = free_gradient_name(&mut self.next_gradient, |name| { - gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some() - }); + let name = + free_gradient_name(&mut self.next_gradient, |name| gradients.has_name(name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()); self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used }); name } @@ -149,14 +276,14 @@ impl Writer<'_> { /// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the /// art uses, and the next name's number. pub(super) fn gradient_mark(&self) -> (usize, Vec, u64) { - (self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient) + (self.gradients.list.len(), self.gradients.list.iter().map(|d| d.used).collect(), self.next_gradient) } /// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]). pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec, u64)) { let (len, used, next) = mark; self.gradients.truncate(len); - for (d, u) in self.gradients.iter_mut().zip(used) { + for (d, u) in self.gradients.list.iter_mut().zip(used) { d.used = u; } self.next_gradient = next; @@ -476,7 +603,7 @@ impl Writer<'_> { if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol { return false; } - if self.patterns.iter().any(|p| p.name == name) { + if self.patterns.find(name).is_some() { return true; } self.doc.pattern(name).is_some_and(tile_holds_art) @@ -492,7 +619,7 @@ impl Writer<'_> { return false; } let used = !self.in_palette; - if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) { + if let Some(p) = self.patterns.find(name).and_then(|i| self.patterns.list.get_mut(i)) { p.used |= used; return true; } @@ -582,7 +709,7 @@ impl Writer<'_> { /// uses). pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) { let defs = std::mem::take(&mut self.gradients); - let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used); + let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.list.iter().partition(|d| d.used); let _ = writeln!(s, "{} Bn", used.len()); for d in &used { self.gradient_def(s, d); @@ -595,12 +722,12 @@ impl Writer<'_> { s.push_str("%AI5_End_NonPrinting--\n"); } self.gradients = defs; - for p in self.patterns.iter().filter(|p| p.used) { + for p in self.patterns.list.iter().filter(|p| p.used) { s.push_str(&p.text); } - if self.patterns.iter().any(|p| !p.used) { + if self.patterns.list.iter().any(|p| !p.used) { s.push_str("%AI5_Begin_NonPrinting\nNp\n"); - for p in self.patterns.iter().filter(|p| !p.used) { + for p in self.patterns.list.iter().filter(|p| !p.used) { s.push_str(&p.text); } s.push_str("%AI5_End_NonPrinting--\n"); @@ -729,3 +856,94 @@ fn tile_holds_art(def: &PatternDef) -> bool { b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1 }) } + +#[cfg(test)] +mod tests { + use super::*; + + fn two(a: f32, b: Color) -> Gradient { + Gradient::new(GradientKind::Linear, vec![GradientStop::new(a, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, b)]) + } + + fn def(name: &str, gradient: Gradient, swatch: bool) -> GradientDef { + GradientDef { name: name.into(), gradient, swatch, used: true } + } + + /// The same gradients have the same key, a zero of either sign included. + #[test] + fn a_zero_of_either_sign_gives_the_same_key() { + assert_eq!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(-0.0, Color::BLACK))); + assert_eq!(two(0.0, Color::BLACK), two(-0.0, Color::BLACK)); + assert_ne!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(0.0, Color::WHITE))); + } + + /// Definitions whose gradients share a key are told apart by their gradients, the first of the + /// same gradient found; a gradient that isn't equal to itself is found in none. + #[test] + fn definitions_that_share_a_key_are_told_apart() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Gradient", white.clone(), false)); + defs.push(def("Gradient 2", black.clone(), false)); + defs.push(def("Gradient 3", black.clone(), false)); + // Every definition under the black gradient's key, as if the keys of both were the same. + defs.ramps = HashMap::from([(gradient_key(&black), vec![0, 1, 2])]); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, None), None); + defs.ramps.insert(gradient_key(&white), vec![0, 1, 2]); + assert_eq!(defs.find(&white, None), Some(0)); + let nan = two(f32::NAN, Color::BLACK); + defs.push(def("Gradient 4", nan.clone(), false)); + assert_eq!(defs.find(&nan, None), None); + } + + /// A swatch's definition is found by the swatch's name and gradient; a definition that no + /// swatch names, for the same gradient without the name or with another. + #[test] + fn a_swatch_definition_is_found_by_its_name_and_gradient() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Ramp", black.clone(), true)); + assert_eq!(defs.find(&black, Some("Ramp")), Some(0)); + assert_eq!(defs.find(&black, None), None); + assert_eq!(defs.find(&white, Some("Ramp")), None); + defs.push(def("Gradient", black.clone(), false)); + defs.push(def("Gradient 2", white.clone(), false)); + assert_eq!(defs.find(&black, Some("Ramp")), Some(0)); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, Some("Ramp")), Some(2)); + assert_eq!(defs.find(&black, Some("Other")), Some(1)); + } + + /// Definitions removed leave their names free and are no longer found; those kept still are. + #[test] + fn removed_definitions_free_their_names() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Ramp", white.clone(), true)); + defs.push(def("Gradient", black.clone(), false)); + defs.push(def("Gradient 2", white.clone(), false)); + defs.push(def("Gradient 3", black.clone(), false)); + defs.truncate(2); + assert!(defs.has_name("Ramp") && defs.has_name("Gradient")); + assert!(!defs.has_name("Gradient 2") && !defs.has_name("Gradient 3")); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, None), None); + assert_eq!(defs.ramps.values().map(Vec::len).sum::(), 1); + defs.push(def("Gradient 2", white.clone(), false)); + assert_eq!(defs.find(&white, None), Some(2)); + defs.truncate(0); + assert!(defs.list.is_empty() && defs.names.is_empty() && defs.ramps.is_empty()); + } + + /// A pattern's definition is found by its name. + #[test] + fn pattern_definitions_are_found_by_name() { + let mut defs = PatternDefs::default(); + assert_eq!(defs.find("Dots"), None); + for name in ["Dots", "Checks"] { + defs.push(PatternOut { name: name.into(), text: String::new(), used: false }); + } + assert_eq!((defs.find("Dots"), defs.find("Checks"), defs.find("Stripes")), (Some(0), Some(1), None)); + } +} diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 50aa4df931..df153c236e 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -2,9 +2,10 @@ //! object itself on `%_` lines and `1 (style) XW`; the styles they name and the Graphic Styles //! panel's styles in `%AI9_BeginArtStyles`, and the panel's order in `%AI9_BeginArtStyleList` (see //! [`crate::ai_editing`] for the form). Each style is read back before it is written -//! ([`crate::import::read_art_style`]: the `.ai` reader's style parser and its reading of a graphic +//! ([`crate::import::read_parsed_style`]: the `.ai` reader's style parser and its reading of a graphic //! style, with the object's own gradient): one that reads back differently is not written, and the -//! object is written as its drawn look alone. +//! object is written as its drawn look alone. Style texts are kept parsed for the save, up to a +//! limit ([`Parsed`]). use std::collections::{HashMap, HashSet}; use std::fmt::Write; @@ -126,7 +127,7 @@ fn candidate(n: &Node) -> bool { /// Is `n` an image, embedded or linked, without an opacity mask whose appearance is one Warp, with /// no fills or strokes that paint and no effects on them: an image the reader reads with its Warp -/// live ([`crate::import::read_art_style`]'s `image_warp`)? +/// live ([`crate::import::read_parsed_style`]'s `image_warp`)? fn warped_image(n: &Node) -> bool { matches!(n.kind, NodeKind::Image(_)) && n.extras().mask.is_none() @@ -162,8 +163,8 @@ fn plain_member(n: &Node) -> bool { pub(in crate::ai_editing) struct Styles { /// Every style, in the order written: its name and text. known: Vec<(String, String)>, - /// The panel's styles written, by the graphic style's id. - panel: HashMap, + /// The panel's styles written, by the graphic style's id: each one's place in [`Self::known`]. + panel: HashMap, /// The panel's styles written, in its order. listed: Vec, /// The names styles have, and the name of each object style by its text. @@ -172,6 +173,54 @@ pub(in crate::ai_editing) struct Styles { next_anon: u64, /// How many objects were written with the graphic style they are linked to. pub(super) links_written: usize, + /// The style texts checked so far, as the reader parses them. + pub(super) parsed: Parsed, +} + +/// The most style texts [`Parsed`] keeps parsed in one save. +const MAX_PARSED: usize = 4096; +/// The most bytes of style text [`Parsed`] keeps parsed in one save. +const MAX_PARSED_BYTES: usize = 8 << 20; + +/// Style texts as the reader parses them ([`crate::import::parse_art_style`]). The first +/// [`MAX_PARSED`] texts, up to [`MAX_PARSED_BYTES`] bytes in all, are each parsed once however many +/// styles and objects are checked with them; a text the reader doesn't parse is kept as `None`. +/// Past that, only the last text checked is kept, and each other text is parsed again when checked. +#[derive(Default)] +pub(super) struct Parsed { + kept: HashMap>, + /// The bytes of the texts in `kept`. + bytes: usize, + /// The last text checked that `kept` doesn't hold, with its parse. + last: Option<(String, Option)>, +} + +#[cfg(test)] +thread_local! { + /// While set on this thread, [`Parsed`] keeps nothing: every check parses its style text again. + pub(in crate::ai_editing) static REPARSE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +impl Parsed { + /// Style text `text` as the reader parses it (`None` when it doesn't). + pub(super) fn get(&mut self, text: &str) -> Option<&crate::import::ParsedStyle> { + #[cfg(test)] + let reparse = REPARSE.get(); + #[cfg(not(test))] + let reparse = false; + if !reparse && self.kept.contains_key(text) { + return self.kept.get(text).and_then(Option::as_ref); + } + if reparse || self.last.as_ref().is_none_or(|(last, _)| last != text) { + let parsed = crate::import::parse_art_style(known_style("x", text).as_bytes(), "x"); + if !reparse && self.kept.len() < MAX_PARSED && self.bytes.saturating_add(text.len()) <= MAX_PARSED_BYTES { + self.bytes += text.len(); + return self.kept.entry(text.to_owned()).or_insert(parsed).as_ref(); + } + self.last = Some((text.to_owned(), parsed)); + } + self.last.as_ref().and_then(|(_, parsed)| parsed.as_ref()) + } } impl Styles { @@ -652,7 +701,7 @@ impl Writer<'_> { continue; } let xy = Xy { blend: g.blend, opacity: g.opacity.clamp(0.0, 1.0), isolate: g.isolate, knockout: g.knockout, shape: false }; - let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t)); + let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t, &mut self.styles.parsed)); let Some(text) = text else { self.warn(PANEL_STYLES); continue; @@ -669,7 +718,7 @@ impl Writer<'_> { continue; } if g.id != 0 { - self.styles.panel.insert(g.id, g.name.clone()); + self.styles.panel.insert(g.id, self.styles.known.len()); } self.styles.listed.push(g.name.clone()); self.styles.known.push((g.name.clone(), text)); @@ -701,14 +750,13 @@ impl Writer<'_> { } let doc = self.doc; if let Some(id) = orig.extras().graphic_style - && let Some(name) = self.styles.panel.get(&id).cloned() + && let Some((name, text)) = self.styles.panel.get(&id).and_then(|i| self.styles.known.get(*i)) && let Some(g) = doc.graphic_style_by_id(id) && g.transparency_matches(orig) && g.appearance_on(orig).approx_eq(&orig.appearance) - && let Some(text) = self.styles.known.iter().find(|(n, _)| *n == name).map(|(_, t)| t.clone()) - && object_reads(orig, &text) + && object_reads(orig, text, &mut self.styles.parsed) { - return Some(name); + return Some(name.clone()); } let brushed = brushed(orig); if (orig.appearance.effects.is_empty() && !brushed) || !(own_style_holds(&orig.appearance) || warped_image(orig)) { @@ -720,7 +768,7 @@ impl Writer<'_> { let rule = object_rule(orig); let text = self .style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))) - .filter(|t| object_reads(orig, t) && (!brushed || self.brushed_style_reads(t))); + .filter(|t| object_reads(orig, t, &mut self.styles.parsed) && (!brushed || self.brushed_style_reads(t))); let Some(text) = text else { if let Some(mark) = saved.0 { self.gradient_rollback(mark); @@ -784,7 +832,12 @@ impl Writer<'_> { if !self.take_objects(1 + own) { return; } - let linked = orig.extras().graphic_style.and_then(|id| self.styles.panel.get(&id)).is_some_and(|p| p == name); + let linked = orig + .extras() + .graphic_style + .and_then(|id| self.styles.panel.get(&id)) + .and_then(|i| self.styles.known.get(*i)) + .is_some_and(|(p, _)| p == name); if linked { self.styles.links_written += 1; } else if brushed(orig) { @@ -937,13 +990,12 @@ fn own_style_holds(ap: &Appearance) -> bool { } /// Does the reader read graphic style `g` from style text `text` as it is? It leaves out a graphic -/// style with a brush on a stroke that paints. -fn panel_reads(g: &GraphicStyle, text: &str) -> bool { +/// style with a brush on a stroke that paints. `parsed` holds the texts already parsed. +fn panel_reads(g: &GraphicStyle, text: &str, parsed: &mut Parsed) -> bool { if g.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && !s.paint.is_none())) { return false; } - let section = known_style("x", text); - let Some(read) = crate::import::read_art_style(section.as_bytes(), "x", None) else { return false }; + let Some(read) = parsed.get(text).and_then(|st| crate::import::read_parsed_style(st, None)) else { return false }; // The opacity within the written number's precision. read.transparency.is_some_and(|t| (t.0 - g.opacity).abs() <= 1e-4 && (t.1, t.2, t.3) == (g.blend, g.isolate, g.knockout)) && same_appearance(&read.appearance, &g.appearance) @@ -952,19 +1004,20 @@ fn panel_reads(g: &GraphicStyle, text: &str) -> bool { /// Does the reader read object `n` written with style text `text` as it is: a path or compound /// path with a style it reads on any object, filled by the non-zero rule when the style fills it, /// or a group with no fills or strokes of its own, with effects that move the outline only where the -/// reader reads them ([`crate::import::style_moves_with`]), or an image ([`warped_image`]) with a +/// reader reads them ([`crate::import::parsed_moves_with`]), or an image ([`warped_image`]) with a /// style of one Warp? The reader takes such an image's Warp where it draws as its drawn look. -fn object_reads(n: &Node, text: &str) -> bool { - let section = known_style("x", text); +/// `parsed` holds the texts already parsed. +fn object_reads(n: &Node, text: &str, parsed: &mut Parsed) -> bool { + let Some(st) = parsed.get(text) else { return false }; let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_))); - let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false }; + let Some(mut read) = crate::import::read_parsed_style(st, own) else { return false }; let group = matches!(n.kind, NodeKind::Group { .. }); let image = matches!(n.kind, NodeKind::Image(_)); if (image && !(read.image_warp && warped_image(n))) || (!image && !read.simple) || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) - || !crate::import::style_moves_with(section.as_bytes(), "x", n) + || !crate::import::parsed_moves_with(st, n) { return false; } @@ -1038,3 +1091,52 @@ pub(super) fn near(a: &Value, b: &Value) -> bool { _ => a == b, } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A style text after its name: a stroke `width` pt wide. + fn stroke_style(width: usize) -> String { + format!( + "/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(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + 2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 R\n0 0 0 0 0 0 1 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/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n" + ) + } + + /// `text` parsed on its own, as the reader parses it. + fn fresh(text: &str) -> String { + format!("{:?}", crate::import::parse_art_style(known_style("x", text).as_bytes(), "x")) + } + + /// A save that checks more distinct style texts than [`Parsed`] keeps, stroke styles and texts + /// that aren't styles, keeps at most [`MAX_PARSED`] texts and [`MAX_PARSED_BYTES`] bytes, and each + /// check still gives the text's own parse, kept or not, the first time and again. + #[test] + fn parsed_styles_kept_in_a_save_stay_within_the_limits() { + let mut parsed = Parsed::default(); + for i in 0..MAX_PARSED + 100 { + let text = if i % 2 == 0 { stroke_style(i + 1) } else { format!("not a style {i}") }; + let got = format!("{:?}", parsed.get(&text).cloned()); + assert_eq!(got, fresh(&text), "{i}"); + assert_eq!(format!("{:?}", parsed.get(&text).cloned()), got, "{i}"); + assert!(parsed.kept.len() <= MAX_PARSED && parsed.bytes <= MAX_PARSED_BYTES, "{i}: {} texts", parsed.kept.len()); + } + assert_eq!(parsed.kept.len(), MAX_PARSED); + for i in [0, 1, MAX_PARSED - 1, MAX_PARSED, MAX_PARSED + 98, MAX_PARSED + 99] { + let text = if i % 2 == 0 { stroke_style(i + 1) } else { format!("not a style {i}") }; + assert_eq!(format!("{:?}", parsed.get(&text).cloned()), fresh(&text), "{i}"); + } + + let mut parsed = Parsed::default(); + let long = |i: usize| format!("{i} {}", "x".repeat(1 << 20)); + for i in 0..MAX_PARSED_BYTES / (1 << 20) + 4 { + assert_eq!(format!("{:?}", parsed.get(&long(i)).cloned()), fresh(&long(i)), "{i}"); + assert!(parsed.bytes <= MAX_PARSED_BYTES, "{i}: {} bytes", parsed.bytes); + assert_eq!(parsed.bytes, parsed.kept.keys().map(String::len).sum::()); + } + assert!(parsed.kept.len() < MAX_PARSED_BYTES / (1 << 20)); + } +} diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 51ef99de2b..2372003cca 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -445,8 +445,9 @@ fn held_aki(v: f64) -> f64 { if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) } } -/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? -pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { +/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? `fonts` holds the +/// fonts already resolved. +fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool { // Small capitals are read back at Document Setup's default size. let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size; // A run's style as the text document holds it: every other attribute at its default. A color @@ -484,7 +485,7 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { ..CharStyle::default() } }; - let run_lost = |s: &CharStyle| { + let mut run_lost = |s: &CharStyle| { let stroked = !s.stroke.is_none(); // Without a stroke, its weight, cap, join and miter limit draw nothing: nothing is lost. let unstroked = CharStyle::default(); @@ -501,7 +502,7 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { }; // A Lab color is written as RGB. let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); - s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !font_kept(&s) + s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !fonts.kept(&s) }; // A paragraph's style as the text document holds it, and its text: aligned to the start of // its direction (Auto) without a direction of its own, it comes back aligned left, which @@ -669,6 +670,84 @@ fn font_kept(st: &CharStyle) -> bool { && face(&family, &style, read.as_deref()) == face(&st.font_family, &st.font_style, st.font_version.as_deref()) } +/// The font fields of a style, as [`ResolvedFonts`] keeps what they resolve to: the family, style +/// and version, and each Variable Font setting as the bits of its value, so two settings that +/// differ are two keys even where they are written as one number. +#[derive(PartialEq, Eq, Hash)] +struct FontKey { + family: String, + style: String, + version: Option, + axes: Vec<(String, u64)>, +} + +impl FontKey { + fn of(st: &CharStyle) -> Self { + FontKey { + family: st.font_family.clone(), + style: st.font_style.clone(), + version: st.font_version.clone(), + axes: st.font_axes.iter().map(|(tag, v)| (tag.clone(), v.to_bits())).collect(), + } + } +} + +/// What one style's font fields resolved to, each with the font database's generation +/// ([`vectorcraft_text::FontDb::generation`]) when it was resolved. +#[derive(Default)] +struct Resolved { + /// Its font record ([`font_name`]). + record: Option<(u64, FontRecord)>, + /// Whether its font comes back as itself ([`font_kept`]). + kept: Option<(u64, bool)>, +} + +/// The fonts of the styles written so far, each resolved once for the whole save. A value is used +/// again only while the font database's generation is the one it was resolved in: fonts added or +/// loaded since then resolve it again. +#[derive(Default)] +struct ResolvedFonts(HashMap); + +#[cfg(test)] +thread_local! { + /// While set on this thread, [`ResolvedFonts`] keeps nothing: every run's font is resolved again. + pub(in crate::ai_editing) static RESOLVE_EACH_RUN: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`ResolvedFonts`] has resolved a font record or checked a font on this thread. + pub(in crate::ai_editing) static FONT_RESOLVES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +impl ResolvedFonts { + /// The value `slot` holds for the font of style `st` when it was resolved in the font + /// database's current generation, else `resolve(st)`, kept for later runs. + fn get(&mut self, st: &CharStyle, slot: fn(&mut Resolved) -> &mut Option<(u64, T)>, resolve: fn(&CharStyle) -> T) -> &T { + let now = vectorcraft_text::FontDb::global().generation(); + let held = slot(self.0.entry(FontKey::of(st)).or_default()); + #[cfg(test)] + if RESOLVE_EACH_RUN.get() { + *held = None; + } + if held.as_ref().is_some_and(|(generation, _)| *generation != now) { + *held = None; + } + let (_, value) = held.get_or_insert_with(|| { + #[cfg(test)] + FONT_RESOLVES.set(FONT_RESOLVES.get() + 1); + (now, resolve(st)) + }); + value + } + + /// The font record of style `st` ([`font_name`]). + fn record(&mut self, st: &CharStyle) -> &FontRecord { + self.get(st, |r| &mut r.record, font_name) + } + + /// Whether the font of style `st` comes back as itself ([`font_kept`]). + fn kept(&mut self, st: &CharStyle) -> bool { + *self.get(st, |r| &mut r.kept, font_kept) + } +} + /// Whether `c` is a strong right-to-left letter (`Some(true)`: Hebrew, Arabic, Syriac, Thaana, NKo /// and their presentation forms) or a strong left-to-right one (`Some(false)`: any other letter). fn strong_direction(c: char) -> Option { @@ -761,6 +840,8 @@ pub(in crate::ai_editing) struct TextDoc { /// reader counts in them. doc_bytes: usize, doc_values: usize, + /// The fonts of the styles written so far, as they resolve. + resolved: ResolvedFonts, } impl TextDoc { @@ -768,9 +849,14 @@ impl TextDoc { self.stories.is_empty() } + /// Has type `t` attributes the text document leaves out ([`loses`])? + pub(in crate::ai_editing) fn loses(&mut self, t: &TextObject) -> bool { + loses(t, &mut self.resolved) + } + /// The index of the font of `st` in the font set. fn font(&mut self, st: &CharStyle) -> i64 { - let font = font_name(st); + let font = self.resolved.record(st); // Two installed versions of one font are two fonts, so each keeps its own `/5`. let same = |f: &FontRecord| { f.name == font.name && f.version == font.version && f.design.iter().map(|v| fixed(*v)).eq(font.design.iter().map(|v| fixed(*v))) @@ -778,7 +864,7 @@ impl TextDoc { let i = match self.fonts.iter().position(same) { Some(i) => i, None => { - self.fonts.push(font); + self.fonts.push(font.clone()); self.fonts.len() - 1 } }; @@ -1157,7 +1243,7 @@ impl TextDoc { if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) { return None; } - let lost = split_differs || texts.iter().any(|t| loses(t)); + let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved)); let frames: Vec = texts.iter().map(|t| self.frame(t, canvas, scale)).collect(); let story = self.story(&whole, &frames, scale); if !self.fits(mark) { @@ -1352,3 +1438,58 @@ pub(in crate::ai_editing) fn stub(s: &mut String, story: usize, frame: usize, t: } s.push_str("2 /TextAntialiasing ,\n;\n"); } + +#[cfg(test)] +mod tests { + use super::*; + + /// A style's font resolved through [`ResolvedFonts`], the first time and again, is the font + /// record and the check [`font_name`] and [`font_kept`] give for it: static and variable fonts, + /// a version of their own, Variable Font settings within and outside the axis's range, not a + /// number, +0 and -0, an axis the font doesn't have, and a family that isn't installed. A font + /// resolved before the font database last changed is resolved again. + #[test] + fn resolved_fonts_are_the_fonts_resolved_for_each_run() { + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let font = |family: &str, style: &str, version: Option<&str>, axes: &[(&str, f64)]| CharStyle { + font_family: family.into(), + font_style: style.into(), + font_version: version.map(str::to_owned), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..CharStyle::default() + }; + let styles = [ + CharStyle::default(), + font("Source Sans 3", "Bold", None, &[]), + font("Inter", "Medium", None, &[]), + font(VARIABLE_FAMILY, "Regular", None, &[]), + font(VARIABLE_FAMILY, "Bold", Some("Version 1.000"), &[]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 650.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 900.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", f64::NAN)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 0.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", -0.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wdth", 80.0), ("wght", 500.0)]), + font("No Such Family", "Bold", None, &[]), + font("No Such Family", "", Some("2.0"), &[]), + ]; + let mut fonts = ResolvedFonts::default(); + for round in ["first", "again"] { + for st in &styles { + assert_eq!(fonts.record(st), &font_name(st), "{round}: {st:?}"); + assert_eq!(fonts.kept(st), font_kept(st), "{round}: {st:?}"); + } + } + assert_eq!(fonts.0.len(), styles.len(), "each style's font fields are a key of their own"); + // What was resolved before the font database last changed is resolved again. + let stale = vectorcraft_text::FontDb::global().generation().wrapping_sub(1); + let wrong = FontRecord { name: "Wrong".into(), truetype: false, design: vec![], version: String::new() }; + for st in &styles { + let held = fonts.0.entry(FontKey::of(st)).or_default(); + (held.record, held.kept) = (Some((stale, wrong.clone())), Some((stale, !font_kept(st)))); + assert_eq!(fonts.record(st), &font_name(st), "{st:?}"); + assert_eq!(fonts.kept(st), font_kept(st), "{st:?}"); + } + } +} diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 0d451ec9da..d835b457c0 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -70,6 +70,8 @@ mod tests_native; #[cfg(test)] mod tests_reads; #[cfg(test)] +mod tests_strings; +#[cfg(test)] mod tests_type1; #[cfg(test)] mod tests_type42; @@ -89,14 +91,14 @@ use obj::PsError; pub use ai::NameEncoding; #[cfg(test)] pub(crate) use ai::objects_read; +#[cfg(test)] +pub(crate) use ai::{ART_STYLE_PARSES, ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ai::{ BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, - MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, blend_reads, - brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, read_art_style, read_brush_object, read_style_list, - style_moves_with, symbol_art_member, turn_brush_art_over, warp_number, + MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, ParsedStyle, + blend_reads, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, parse_art_style, parsed_moves_with, + read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, }; -#[cfg(test)] -pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 78990f9db7..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; @@ -57,15 +59,17 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, - slot_of, style_moves_with, symbol_art_member, + BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, read_over_page, + read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, read_beside, read_in, symbols, variables, }; +#[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/brush.rs b/crates/eps/src/import/ai/brush.rs index ef45364de5..da7f4c3576 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -63,7 +63,7 @@ use std::sync::Arc; use kurbo::Affine; use vectorcraft_brush::{ArtBrush, ArtScale, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; use vectorcraft_color::Paint; -use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind, Scaling}; use super::lex::{Lexer, Tok}; use super::obj::Names; @@ -475,10 +475,11 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result< Ok(BrushDraft { name: name.to_string(), kind }) } -/// Turn `art` over (y for -y) with the art of all its opacity masks, those that don't move with -/// their objects too: the art changes the space it is in, and no object moves over its mask. +/// Turn `art` over (y for -y) with its pattern fills' tiles and the art of all its opacity masks, +/// those that don't move with their objects too: the art changes the space it is in, and no object +/// moves over its tiles or its mask. pub(crate) fn turn_over(art: &mut Node) { - art.transform(Affine::scale_non_uniform(1.0, -1.0), false); + art.transform(Affine::scale_non_uniform(1.0, -1.0), Scaling { patterns: true, ..Scaling::default() }); turn_unlinked_masks(art); } @@ -574,7 +575,12 @@ pub(super) fn finish_brushes_within( let kind = match d.kind { _ if !kept => None, DraftKind::Calligraphic(c) => Some(BrushKind::Calligraphic(c)), - DraftKind::Scatter { brush, art: name } => copy(&name).map(|a| BrushKind::Scatter(Scatter { art: a, ..brush })), + DraftKind::Scatter { brush, art: name } => copy(&name).map(|mut a| { + // Each copy is the section turned over: its side with y up draws down the page + // before the copy's rotation, and a brush draws art's y (down here) down the page. + turn_over(&mut a); + BrushKind::Scatter(Scatter { art: a, ..brush }) + }), DraftKind::Art { mut brush, art: name, settings } => copy(&name).map(|mut a| { // The side of the section with y up draws on the right of the path, and a brush // draws art's y (down here) on the left of the path. @@ -799,14 +805,16 @@ impl BrushesRead { Self { drafts, by_name, bending } } - /// Does the reader read every stroke of art style `style` in `section` (the text between - /// `%AI9_BeginArtStyles` and its end) that names a brush with that brush on it, at the brush's - /// own settings? A style the reader doesn't read, or that names a brush no object gives, or an - /// Art brush in a style with effects, isn't read so. - pub(crate) fn style_reads(&self, section: &[u8], style: &str) -> bool { + /// Does the reader read every stroke of art style `parsed` ([`crate::import::parse_art_style`]) + /// that names a brush with that brush on it, at the brush's own settings? A style the reader + /// doesn't read, or that names a brush no object gives, or an Art brush in a style with effects, + /// isn't read so. + pub(crate) fn style_reads(&self, parsed: &crate::import::ParsedStyle) -> bool { use super::style::StyleItem; - let styles = super::style::art_styles(section); - let Some(st) = styles.get(style).filter(|st| st.plain) else { return false }; + let st = &parsed.style; + if !st.plain { + return false; + } st.items.iter().all(|item| match item { StyleItem::Stroke { brush: Some((name, settings)), .. } => { let Some(draft) = self.by_name.get(name).and_then(|i| self.drafts.get(*i)) else { return false }; 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 27a10033db..b354022258 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -155,7 +155,7 @@ pub use document::{ }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; -pub(crate) use ops::{read_art_style, read_style_list, style_moves_with}; +pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; @@ -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..3dd44b3162 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 { @@ -134,6 +137,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 +191,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); } 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 39499b064d..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 @@ -1453,16 +1622,30 @@ pub(crate) fn read_style_list(section: &[u8]) -> Vec { crate::import::ai::style::art_style_list(section).iter().map(|raw| obj::text(raw)).filter(|name| !name.is_empty()).collect() } -/// Art style `name` of `section` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], -/// with a style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads -/// it on objects other than type. A stroke that names a brush is read with that brush's name, as -/// [`styled`] reads it on a path or compound path when the Brushes panel keeps that brush at those -/// settings, which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the section -/// doesn't define it, the reader doesn't read it, or it paints with a pattern or a gradient that -/// isn't the object's own. -pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&Paint>) -> Option { +/// An art style as the reader parses it ([`parse_art_style`]), which a writer reads on any number of +/// objects ([`read_parsed_style`], [`parsed_moves_with`], +/// [`crate::import::ai::brush::BrushesRead::style_reads`]). +#[derive(Clone, Debug)] +pub(crate) struct ParsedStyle { + pub(in crate::import::ai) style: crate::import::ai::style::ArtStyle, +} + +/// Art style `name` of `section` (the text between `%AI9_BeginArtStyles` and its end) as the reader +/// parses it. `None` when the section doesn't define it. +pub(crate) fn parse_art_style(section: &[u8], name: &str) -> Option { + crate::import::ai::style::art_styles(section).remove(name).map(|style| ParsedStyle { style }) +} + +/// Art style `parsed` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], with a +/// style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads it on +/// objects other than type. A stroke that names a brush is read with that brush's name, as [`styled`] +/// reads it on a path or compound path when the Brushes panel keeps that brush at those settings, +/// which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the reader doesn't +/// read it, or it paints with a pattern or a gradient that isn't the object's own. `parsed` is left as +/// it is, for the next object. +pub(crate) fn read_parsed_style(parsed: &ParsedStyle, own_gradient: Option<&Paint>) -> Option { use crate::import::ai::style::StyleItem; - let mut st = crate::import::ai::style::art_styles(section).remove(name)?; + let mut st = parsed.style.clone(); if st.items.iter().filter(|i| matches!(i, StyleItem::Gradient { .. })).count() == 1 { let own = own_gradient?; for item in &mut st.items { @@ -1491,11 +1674,10 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P Some(StyleRead { appearance, simple: st.simple, image_warp: st.image_warp, pathfinder: st.pathfinder, transparency: st.transparency }) } -/// Is art style `name` of `section` read on `object` as far as an effect that moves the outline -/// goes: the style has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? -/// `false` when the section doesn't define it. -pub(crate) fn style_moves_with(section: &[u8], name: &str, object: &Node) -> bool { - crate::import::ai::style::art_styles(section).remove(name).is_some_and(|st| !st.moves_outline() || moves_with(object, &st)) +/// Is art style `parsed` read on `object` as far as an effect that moves the outline goes: the style +/// has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? +pub(crate) fn parsed_moves_with(parsed: &ParsedStyle, object: &Node) -> bool { + !parsed.style.moves_outline() || moves_with(object, &parsed.style) } /// A style's stroke as an appearance item (`None` for a fill). @@ -1660,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 e0068a52be..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 @@ -419,8 +420,16 @@ fn closes(data: &[u8]) -> bool { false } +#[cfg(test)] +thread_local! { + /// How many times [`art_styles`] has parsed a section on this thread. + pub(crate) static ART_STYLE_PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// [`art_styles_in`], names read in the default encoding. pub(super) fn art_styles(data: &[u8]) -> HashMap { + #[cfg(test)] + ART_STYLE_PARSES.set(ART_STYLE_PARSES.get() + 1); art_styles_in(data, &mut Names::default()) } @@ -1461,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(), @@ -1473,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, @@ -1736,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() { @@ -1754,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), @@ -1853,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 c4b006fe2a..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")]; @@ -1445,7 +1450,8 @@ fn warp_numbers_are_the_dialogs_order() { /// and nothing for styles it doesn't read. #[test] fn a_style_is_read_as_a_writer_checks_it() { - let read = |data: &str, own: Option<&Paint>| crate::import::read_art_style(data.as_bytes(), "Odd", own); + let parse = |data: &str, name: &str| crate::import::parse_art_style(data.as_bytes(), name); + let read = |data: &str, own: Option<&Paint>| parse(data, "Odd").and_then(|st| crate::import::read_parsed_style(&st, own)); let style = |kids: &[String]| format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", kids)); let gradient = fill("Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB"); let stack = compound("Stack Style Filter", std::slice::from_ref(&gradient)); @@ -1456,11 +1462,18 @@ fn a_style_is_read_as_a_writer_checks_it() { assert_eq!(got.appearance.items[0].paint(), &own); assert_eq!(got.transparency.map(|t| (t.0, t.1)), Some((0.5, BlendMode::Multiply))); assert!(got.simple && !got.pathfinder); + // One parse read on two objects: each takes its own gradient, and the parse is left as it was. + let parsed = parse(&data, "Odd").unwrap(); + let black = Paint::solid(vectorcraft_color::Color::BLACK); + let first = crate::import::read_parsed_style(&parsed, Some(&own)).unwrap(); + let second = crate::import::read_parsed_style(&parsed, Some(&black)).unwrap(); + assert_eq!((first.appearance.items[0].paint(), second.appearance.items[0].paint()), (&own, &black)); + assert_eq!(parsed.style, parse(&data, "Odd").unwrap().style); // A gradient that isn't the object's own, a pattern, another name, two gradients: nothing. assert!(read(&data, None).is_none()); let pattern = style(&[compound("Stack Style Filter", &[fill("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p")])]); assert!(read(&pattern, None).is_none()); - assert!(crate::import::read_art_style(data.as_bytes(), "Even", Some(&own)).is_none()); + assert!(parse(&data, "Even").is_none()); assert!(read(&style(&[compound("Stack Style Filter", &[gradient.clone(), gradient])]), Some(&own)).is_none()); // Damaged text: every cut of the style, and stray bytes, without a panic. for cut in 0..data.len() { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 5b3f62f03e..b1ee117e2a 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() { @@ -2507,6 +2692,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 +3957,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 +6552,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 +6567,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 +7630,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 +9128,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 +9901,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 @@ -10483,11 +10881,11 @@ fn a_brushs_art_places_a_version_7_patterns_tiles_with_its_operands() { }; let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"); // The operands and the move they make from the plain placement (a b c d e f): those of - // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` with y down, as the - // art's space has it. + // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` in the file's own + // space (y up), since a Scatter brush's art is turned over with its tiles. let cases = [ - ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, -15.0]), - ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, 0.353553, -1.035276, 0.353553, -5.0, -7.0]), + ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, 15.0]), + ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, -0.353553, 1.035276, 0.353553, -5.0, 7.0]), ]; for (ops, want) in cases { let got = (placed(ops) * plain.inverse()).as_coeffs(); @@ -11325,6 +11723,103 @@ fn type_with_an_art_brush_keeps_its_drawn_look() { assert_eq!(brushed, 0, "{:?}", r.warnings); } +/// Each copy a Scatter brush places is its section's art turned over before the copy's rotation: +/// the side of the section with y up goes down the page with the rotation at 0° to the page, and +/// to the right of the path's direction when the rotation follows the path. A rotation turns the +/// copy counterclockwise on the page, from the page or from the path's direction. +#[test] +fn a_scatter_brushs_copies_are_its_art_turned_over() { + // Size, spacing 100% and scatter 0%, fixed; the rotation 0° or 90°, to the page or following + // the path. + let still = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0"; + let turned = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 90 90 0 0 0"; + let along = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 1 0"; + let def = format!( + "{}{}{}{}", + lopsided_art("Lopsided art"), + plugin_object(SCATTER, "Still", still), + plugin_object(SCATTER, "Turned", turned), + plugin_object(SCATTER, "Along", along) + ); + let r = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + let lib = vectorcraft_brush::library(&r.doc); + let stroke = vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 1.0); + // The art is 40 by 8, so copies are 40 apart along a line 100 long, centered at 20, 60 and 100 + // from its start. + let pieces = |name: &str, from: (f64, f64), to: (f64, f64)| { + let b = lib.iter().find(|b| b.name == name).unwrap(); + let line = kurbo::BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(from.0, from.1)), kurbo::PathEl::LineTo(Point::new(to.0, to.1))]); + vectorcraft_brush::stroke_pieces(&r.doc, b, &line, &stroke) + }; + let filled = |pieces: &[Node], x: f64, y: f64| { + pieces.iter().any(|n| { + let mut hit = false; + n.walk(&mut |c| hit |= c.path_data().is_some_and(|p| kurbo::Shape::winding(&p.to_bezpath(), Point::new(x, y)) != 0)); + hit + }) + }; + let still = pieces("Still", (0.0, 0.0), (100.0, 0.0)); + assert_eq!(still.len(), 3, "{still:#?}"); + // The copy at 60 spans 40 to 80: the narrow block is its first 10, the wide block all of it. + assert!(filled(&still, 70.0, -2.0) && !filled(&still, 70.0, 2.0), "the wide block is above the line"); + assert!(filled(&still, 45.0, 2.0), "the narrow block is below it"); + // Turned 90° to the page, the copy at 60 stands across the line from 40 above it to 80 below + // it: the wide block on the left, the narrow block on the right at its bottom 10. + let turned = pieces("Turned", (0.0, 0.0), (100.0, 0.0)); + assert_eq!(turned.len(), 3, "{turned:#?}"); + assert!(filled(&turned, 58.0, 0.0) && !filled(&turned, 62.0, 0.0), "the wide block is left of the copy's middle"); + assert!(filled(&turned, 62.0, 15.0) && !filled(&turned, 62.0, -15.0), "the narrow block is at its bottom"); + // Right to left with the rotation following the path, the copy at 40 (20 to 60) is turned half + // way round: its narrow block is its last 10. + let along = pieces("Along", (100.0, 0.0), (0.0, 0.0)); + assert_eq!(along.len(), 3, "{along:#?}"); + assert!(filled(&along, 30.0, 2.0) && !filled(&along, 30.0, -2.0), "the wide block is below the line"); + assert!(filled(&along, 55.0, -2.0), "the narrow block is above it, at the copy's other end"); + // Up the page with the rotation following the path, the copy at y 40 (20 to 60) is turned a + // quarter round: the wide block on the left of the line, the narrow block on its right at its + // bottom 10, where the line starts. + let up = pieces("Along", (0.0, 100.0), (0.0, 0.0)); + assert_eq!(up.len(), 3, "{up:#?}"); + assert!(filled(&up, -2.0, 40.0) && !filled(&up, 2.0, 40.0), "the wide block is left of the line"); + assert!(filled(&up, 2.0, 55.0) && !filled(&up, 2.0, 25.0), "the narrow block is right of it, at the copy's bottom"); +} + +/// A pattern fill in a Scatter or Art brush's art is turned over with the art: the tiles keep their +/// place on the art. The section fills a 40 by 8 rectangle with an 8-point tile placed with the +/// identity, so the tile's top left is at the rectangle's top left in the section (y up). +#[test] +fn a_pattern_fill_in_brush_art_turns_over_with_the_art() { + let still = "2 /Tiled art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0"; + let ribbon = "2 / Tiled art/ / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1"; + let section = format!( + "%AI8_BeginBrushPattern\n(Tiled art)\n0 A\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n%AI8_EndBrushPattern\n", + rect_path(0.0, 0.0, 40.0, 8.0) + ); + let def = format!("{DOTS}{section}{}{}", plugin_object(SCATTER, "Spray", still), plugin_object(ART_BRUSH, "Ribbon", ribbon)); + let r = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + let lib = vectorcraft_brush::library(&r.doc); + for name in ["Spray", "Ribbon"] { + let b = lib.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("{name}: {lib:?}")); + let art = match &b.kind { + vectorcraft_brush::BrushKind::Scatter(s) => &s.art, + vectorcraft_brush::BrushKind::Art(a) => &a.art, + k => panic!("{name}: {k:?}"), + }; + let mut found = None; + art.walk(&mut |n| { + if let (Some(_), Paint::Pattern { xf, .. }) = (n.path_data(), fill(n)) { + found = Some((n.geometric_bounds(), xf)); + } + }); + let Some((Some(bounds), xf)) = found else { panic!("{name}: {art:#?}") }; + // The art is turned over (y up again): the tile's top left (0, 0) and its dot (4, 4), in + // the tile's space with y down, are at the rectangle's top left and 4 below it. + assert_eq!(bounds, Rect::new(0.0, 0.0, 40.0, 8.0), "{name}"); + assert!((xf * Point::ZERO - Point::new(0.0, bounds.y1)).hypot() < 1e-9, "{name}: {xf:?}"); + assert!((xf * Point::new(4.0, 4.0) - Point::new(4.0, bounds.y1 - 4.0)).hypot() < 1e-9, "{name}: {xf:?}"); + } +} + use read::{GRAPH_PLAIN, GRAPH_UNENDED}; use vectorcraft_doc::{GraphKind, TickLength}; diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 5fdd5859a9..96a408ae7d 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -65,6 +65,14 @@ impl Val { } } + /// Removes the entry `key` of a dictionary and returns it, without copying it. + fn take(&mut self, key: &str) -> Option { + match self { + Val::Dict(d) => d.remove(key), + _ => None, + } + } + fn num(&self) -> Option { match self { Val::Num(n) if n.is_finite() => Some(*n), @@ -86,6 +94,14 @@ impl Val { } } + /// [`Self::list`] as an owned vector, without copying the items: empty when this isn't a list. + fn into_list(self) -> Vec { + match self { + Val::List(l) => l, + _ => Vec::new(), + } + } + fn nums(&self) -> Option> { self.list().iter().map(Val::num).collect() } @@ -661,20 +677,30 @@ impl Texts { }) .collect(); let main = doc.get("1")?; + main.get("1")?; + main.get("2")?; + doc.get("0")?.get("8")?.get("0")?; let sheets = |key: &str| -> Vec { let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() }; + let char_sheets = sheets("5"); + let para_sheets = sheets("6"); + let kinsoku_sets = kinsoku_sets(&doc); + // Every path is there (looked up above), so the stories, defaults and frames move out of the + // document without a copy. + let mut doc = doc; + let mut main = doc.take("1")?; Some(Texts { - stories: main.get("1")?.list().to_vec(), + stories: main.take("1")?.into_list(), fonts, - defaults: main.get("2")?.clone(), - para_defaults: main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), - char_sheets: sheets("5"), - para_sheets: sheets("6"), - frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(), + defaults: main.take("2")?, + para_defaults: main.take("3").unwrap_or(Val::Dict(BTreeMap::new())), + char_sheets, + para_sheets, + frames: doc.take("0")?.take("8")?.take("0")?.into_list(), patterns: HashMap::new(), - kinsoku_sets: kinsoku_sets(&doc), + kinsoku_sets, }) } @@ -3086,4 +3112,100 @@ mod tests { let (placed, at, _) = first(&s, true); assert!(placed && at.is_some_and(|x| (x - (own + 3.0)).abs() < 1e-6), "{at:?} for {}", own + 3.0); } + + /// [`Val::take`] and [`Val::into_list`] hand over the value they find without copying it. + #[test] + fn taking_a_value_keeps_its_storage() { + let mut v = read(b"/1 [ (a story) << /0 (its frame) >> ] /2 (defaults)").unwrap(); + let (Some(Val::List(l)), Some(Val::Str(s))) = (v.get("1"), v.get("2")) else { panic!("a list and a string") }; + let (list, string) = (l.as_ptr(), s.as_ptr()); + let taken = v.take("1").unwrap().into_list(); + assert_eq!(taken.as_ptr(), list); + assert_eq!(taken.len(), 2); + let Some(Val::Str(s)) = v.take("2") else { panic!("a string") }; + assert_eq!(s.as_ptr(), string); + assert_eq!(v, Val::Dict(BTreeMap::new())); + assert_eq!(v.take("1"), None); + assert_eq!(Val::Num(1.0).take("1"), None); + assert_eq!(Val::Str("x".into()).into_list(), Vec::new()); + } + + /// [`Texts::read`] gives the same stories, defaults, frames, styles, Kinsoku sets and fonts as + /// copying each of them out of the parsed document does, and reads nothing where that finds + /// nothing. + #[test] + fn the_text_document_reads_the_same_as_copying_its_parts() { + type Parts = (Vec, Val, Val, Vec, Vec, Vec, Vec>, Vec<(String, Option)>); + let copied = |document: &str| -> Option { + let doc = names::numbered(read(document.as_bytes())?); + let fonts = doc.get("0")?.get("1")?.get("0")?.list(); + let fonts = fonts + .iter() + .map(|f| { + let record = f.get("0").and_then(|f| f.get("0")); + let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); + (text("0").unwrap_or_default().to_string(), text("5").and_then(record_version).map(str::to_string)) + }) + .collect(); + let main = doc.get("1")?; + let sheets = |key: &str| -> Vec { + let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); + list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() + }; + Some(( + main.get("1")?.list().to_vec(), + main.get("2")?.clone(), + main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), + doc.get("0")?.get("8")?.get("0")?.list().to_vec(), + sheets("5"), + sheets("6"), + kinsoku_sets(&doc), + fonts, + )) + }; + let read_parts = |document: &str| -> Option { + // Padded so that the data's end, `~>`, stays on one line. + let mut document = document.to_string(); + while crate::import::tests_native::native_with_text("", &document).contains("\n%>\n") { + document.push('\n'); + } + let t = Texts::read(crate::import::tests_native::native_with_text("", &document).as_bytes())?; + let fonts = t.fonts.iter().map(|f| (f.name.clone(), f.version.clone())).collect(); + Some((t.stories, t.defaults, t.para_defaults, t.frames, t.char_sheets, t.para_sheets, t.kinsoku_sets, fonts)) + }; + let plain = crate::import::tests_native::text_document(&[ + ("First story", 0, (10.0, 20.0), (1.0, 2.0), 0.0), + ("Second, longer story", 2, (30.0, 40.0), (3.0, 4.0), 5.0), + ("Third", 1, (50.0, 60.0), (5.0, 6.0), 0.0), + ]); + let full = plain + .replacen( + "/8 << /0 [", + "/4 << /0 [ << /0 << /0 (PhotoshopKinsokuHard) >> >> << /0 << /0 (Own) >> >> ] >> \ + /5 << /0 [ << /0 << /0 (Normal) /6 << /1 9.0 >> >> >> << /1 0 >> ] >> \ + /6 << /0 [ << /0 << /0 (Body) /5 << /0 2 >> >> >> ] >> /8 << /0 [", + 1, + ) + .replacen("/2 << /1 12.0 >>", "/2 << /1 12.0 /0 1 >> /3 << /0 2 /33 1 >>", 1); + let cases = [ + ("every part", full.clone(), true), + ("no paragraph defaults", plain.clone(), true), + ("stories that aren't a list", full.replacen("\n/1 << /1 [", "\n/1 << /1 5 /7 [", 1), true), + ("frames that aren't a list", full.replacen("/8 << /0 [", "/8 << /0 5 /7 [", 1), true), + ("no defaults", full.replacen("/2 << /1 12.0 /0 1 >>", "", 1), false), + ("no frames", full.replacen("/8 << /0 [", "/9 << /0 [", 1), false), + ("no stories", full.replacen("\n/1 << /1 [", "\n/1 << /7 [", 1), false), + ("no fonts", full.replacen("/0 << /1 << /0 [", "/0 << /1 << /7 [", 1), false), + ]; + for (case, document, reads) in cases { + assert!(case == "every part" || document != full, "{case} changes the document"); + let want = copied(&document); + assert_eq!(want.is_some(), reads, "{case}"); + assert_eq!(read_parts(&document), want, "{case}"); + } + let Some((stories, defaults, para_defaults, frames, char_sheets, para_sheets, kinsoku, fonts)) = read_parts(&full) else { panic!("read") }; + assert_eq!((stories.len(), frames.len(), char_sheets.len(), para_sheets.len(), fonts.len()), (3, 3, 2, 1, 1)); + assert_eq!(kinsoku, [Some(Kinsoku::Hard), None]); + assert!(defaults.get("0").is_some() && para_defaults.get("33").is_some()); + } } diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index c4fc09e0b0..cca8bb50ea 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -146,13 +146,21 @@ impl Interp<'_> { fn token(&mut self) -> Res { match self.pop()? { Obj::Str(s) => { - let bytes = s.to_vec(); - let mut lex = Lexer::new(&bytes); - let Some(o) = lex.next()? else { return self.push(Obj::Bool(false)) }; - let o = self.scanned(o, lex.immediate)?; - // The whitespace after the token is read with it. - let used = bytes.len() - lex.data().len(); - self.push_interval(Obj::Str(s), used, bytes.len() - used)?; + // The scanner reads the string in place. The borrow ends before `scanned`, which + // can fail or charge the budget, and before the results are pushed. + let read = { + let bytes = s.borrow(); + let mut lex = Lexer::new(&bytes); + // The whitespace after the token is read with it. + lex.next()?.map(|o| { + let immediate = lex.immediate; + let rest = lex.data().len(); + (o, immediate, bytes.len() - rest, rest) + }) + }; + let Some((o, immediate, used, rest)) = read else { return self.push(Obj::Bool(false)) }; + let o = self.scanned(o, immediate)?; + self.push_interval(Obj::Str(s), used, rest)?; self.push(o)?; } Obj::File { stream: f, .. } => { 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/interp.rs b/crates/eps/src/import/interp.rs index 43346988ff..8d883a0bff 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -753,21 +753,25 @@ impl<'a> Interp<'a> { } fn search_string(&mut self, op: Op) -> Res { - let seek = self.pop_str()?.to_vec(); + let seek = self.pop_str()?; let s = self.pop_str()?; - let text = s.to_vec(); - self.spend((text.len() / 64) as u64)?; - let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + // Both strings are read in place, and the borrows end before the results are pushed. + let (len, n, at) = { + let (text, seek) = (s.borrow(), seek.borrow()); + self.spend((text.len() / 64) as u64)?; + let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + (text.len(), seek.len(), at) + }; match at { Some(i) => { let o = Obj::Str(s); if op == Op::Search { - self.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?; - self.push_interval(o.clone(), i, seek.len())?; + self.push_interval(o.clone(), i + n, len - i - n)?; + self.push_interval(o.clone(), i, n)?; self.push_interval(o, 0, i)?; } else { - self.push_interval(o.clone(), seek.len(), text.len() - seek.len())?; - self.push_interval(o, 0, seek.len())?; + self.push_interval(o.clone(), n, len - n)?; + self.push_interval(o, 0, n)?; } self.push(Obj::Bool(true))?; } 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/obj.rs b/crates/eps/src/import/obj.rs index 2b3ae92c73..1fcd41dd85 100644 --- a/crates/eps/src/import/obj.rs +++ b/crates/eps/src/import/obj.rs @@ -49,6 +49,8 @@ thread_local! { /// Tests: the arrays of the list last released on this thread that were still alive after it /// (the ones the interpreter itself still held). pub(crate) static ARRAYS_LEFT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many values [`Shared::to_vec`] has copied on this thread. + pub(crate) static VALUES_COPIED: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { @@ -340,7 +342,10 @@ impl Shared { } pub fn to_vec(&self) -> Vec { - self.borrow().to_vec() + let v = self.borrow().to_vec(); + #[cfg(test)] + VALUES_COPIED.with(|n| n.set(n.get() + v.len())); + v } /// `n` values from `at`, sharing the storage (`getinterval`); `None` past the end. 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/import/tests_strings.rs b/crates/eps/src/import/tests_strings.rs new file mode 100644 index 0000000000..2a07dafd7c --- /dev/null +++ b/crates/eps/src/import/tests_strings.rs @@ -0,0 +1,306 @@ +//! `token` on a string, `search` and `anchorsearch` (PLRM 3rd ed., pp. 702-703, 655 and 529) read +//! their strings in place. The tests run them next to reference readers that copy the strings +//! first, on the same operands in the same interpreter state: the operand stack, the error and the +//! operations spent must agree. + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::time::{Duration, Instant}; + +use vectorcraft_doc::Document; +use vectorcraft_geom::{Affine, Rect}; + +use super::graphics::{GState, Out}; +use super::interp::Interp; +use super::lex::Lexer; +use super::obj::{Obj, Op, PsError, Res, Shared, VALUES_COPIED}; + +/// An interpreter that has run `src`, with the operands it left. +fn after(src: &[u8]) -> Interp<'_> { + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0))); + assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src)); + it +} + +/// The reference `token`: the string copied before it is scanned. +fn token_by_copy(it: &mut Interp) -> Res { + match it.pop()? { + Obj::Str(s) => { + let bytes = s.to_vec(); + let mut lex = Lexer::new(&bytes); + let Some(o) = lex.next()? else { return it.push(Obj::Bool(false)) }; + let o = it.scanned(o, lex.immediate)?; + let used = bytes.len() - lex.data().len(); + it.push_interval(Obj::Str(s), used, bytes.len() - used)?; + it.push(o)?; + } + Obj::File { stream: f, .. } => { + let (o, immediate) = it.next_in(&f)?; + let Some(o) = o else { return it.push(Obj::Bool(false)) }; + let o = it.scanned(o, immediate)?; + it.push(o)?; + } + _ => return Err(PsError::Ps("typecheck", "token".into())), + } + it.push(Obj::Bool(true)) +} + +/// The reference `search` and `anchorsearch`: both strings copied before they are compared. +fn search_by_copy(it: &mut Interp, op: Op) -> Res { + let seek = it.pop_str()?.to_vec(); + let s = it.pop_str()?; + let text = s.to_vec(); + it.spend((text.len() / 64) as u64)?; + let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + match at { + Some(i) => { + let o = Obj::Str(s); + if op == Op::Search { + it.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?; + it.push_interval(o.clone(), i, seek.len())?; + it.push_interval(o, 0, i)?; + } else { + it.push_interval(o.clone(), seek.len(), text.len() - seek.len())?; + it.push_interval(o, 0, seek.len())?; + } + it.push(Obj::Bool(true))?; + } + None => { + it.push(Obj::Str(s))?; + it.push(Obj::Bool(false))?; + } + } + Ok(()) +} + +fn by_copy(it: &mut Interp, op: Op) -> Res { + if op == Op::Token { token_by_copy(it) } else { search_by_copy(it, op) } +} + +/// The error's name, or the limit reached. +fn outcome(r: Res) -> Result<(), String> { + r.map_err(|e| match e { + PsError::Ps(name, _) => name.to_string(), + e => format!("{e:?}"), + }) +} + +/// Everything the operator left: the operand stack with each string's storage, offset and length, +/// and the operations spent. +fn state(it: &Interp) -> (String, u64) { + (format!("{:?}", it.stack), it.ops_left()) +} + +/// Run `op` on the operands `src` leaves, in place and by copy, `steps` times (a walk that feeds +/// each call the string the last one left), and check that the two agree after every call. +fn agree(src: &str, op: Op, steps: usize) { + let (mut new, mut old) = (after(src.as_bytes()), after(src.as_bytes())); + // `search` and `anchorsearch` look for the same string on each call. + let seeks = [new.stack.last().cloned(), old.stack.last().cloned()]; + for step in 0..steps { + let (a, b) = (outcome(new.op(op)), outcome(by_copy(&mut old, op))); + assert_eq!(a, b, "{src} {op:?}, call {step}"); + assert_eq!(state(&new), state(&old), "{src} {op:?}, call {step}"); + // Keep walking while the operator answered true, with the string it left. + let more = matches!(new.stack.last(), Some(Obj::Bool(true))); + if a.is_err() || !more { + break; + } + for (it, seek) in [&mut new, &mut old].into_iter().zip(&seeks) { + it.stack.pop(); + // `token` leaves the rest under the object; `search` leaves it under match and pre + // (and `anchorsearch` under the match). + let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 }; + it.stack.truncate(keep); + // The string to look for again, or the file `token` reads on from. + if op != Op::Token || matches!(seek, Some(Obj::File { .. })) { + it.stack.extend(seek.clone()); + } + } + } + new.release(); + old.release(); +} + +#[test] +fn token_and_search_agree_with_copying_readers() { + let tokens = [ + "()", + "( )", + "(\r\n\t )", + "(12)", + "(12 34)", + "(12 34)", + "(12\r\n34)", + "(/x {a b} (s) <41> 1.5 x)", + "(1 {)", + "( [ 1 ] )", + "/x 7 def (//x {//x} y)", + "(xx12 34 56) 2 7 getinterval", + "(%comment only)", + "5", + "(12 /x {a}) /ReusableStreamDecode filter", + "currentfile", + ]; + for src in tokens { + agree(src, Op::Token, 16); + } + let searches = [ + "(abcabc) (bc)", + "(abc) (x)", + "(abc) ()", + "() ()", + "() (a)", + "(ab) (abc)", + "(a\nb\nc\n) (\n)", + "/s (aa) def s s", + "(xxab cd ef) 2 8 getinterval ( )", + "(abc) 5", + "5 (abc)", + ]; + for src in searches { + agree(src, Op::Search, 8); + agree(src, Op::AnchorSearch, 8); + } + // Over the operation budget: the same error, with the same operands popped. + let big = "/h 65536 string def h (\\001)"; + let (mut new, mut old) = (after(big.as_bytes()), after(big.as_bytes())); + for it in [&mut new, &mut old] { + let left = it.ops_left(); + assert_eq!(it.spend(left.saturating_sub(10)), Ok(())); + } + let (a, b) = (outcome(new.op(Op::Search)), outcome(by_copy(&mut old, Op::Search))); + assert!(a.as_ref().is_err_and(|e| e.contains("too long")), "{a:?}"); + assert_eq!((a, state(&new)), (b, state(&old))); + new.release(); + old.release(); +} + +/// The results share the string's storage: a write to the string after `token` or `search` shows +/// in what they left. +#[test] +fn token_and_search_results_see_later_writes() { + let check = super::tests::check; + check("/s (12 34) def s token pop pop /post exch def s 3 57 put post token pop exch pop 94 eq"); + check("/s (ab cd) def s ( ) search pop /pre exch def pop /post exch def s 0 120 put s 4 121 put pre (xb) eq post (cy) eq and"); + check("/s (ab cd) def s (ab) anchorsearch pop pop /post exch def s 4 122 put post ( cz) eq"); + check("/s (xx12 34) def s 2 5 getinterval token pop pop /post exch def s 5 57 put post token pop exch pop 94 eq"); +} + +/// `token` on a string, `search` and `anchorsearch` copy neither string. +#[test] +fn token_and_search_copy_no_string() { + for (src, op) in [ + ("(12 34 56 78)", Op::Token), + ("(abc def ghi) ( )", Op::Search), + ("(abc def ghi) (xyz)", Op::Search), + ("(abc def ghi) (abc)", Op::AnchorSearch), + ("(abc def ghi) (def)", Op::AnchorSearch), + ] { + let mut it = after(src.as_bytes()); + VALUES_COPIED.with(|n| n.set(0)); + assert_eq!(it.op(op), Ok(()), "{src} {op:?}"); + assert_eq!(VALUES_COPIED.with(std::cell::Cell::get), 0, "{src} {op:?}"); + it.release(); + } +} + +/// The median of `runs`. +fn median(runs: &[Duration]) -> Duration { + let mut sorted = runs.to_vec(); + sorted.sort(); + sorted.get(sorted.len() / 2).copied().unwrap_or_default() +} + +/// What a walk records of each result: a string's length and first bytes, any other object whole. +fn mark(o: &Obj, h: &mut impl Hasher) { + match o { + Obj::Str(s) => { + s.len().hash(h); + s.borrow().iter().take(16).for_each(|b| b.hash(h)); + } + o => format!("{o:?}").hash(h), + } +} + +/// Walk `data` with `op` and `seek` (none for `token`) until the operator answers false, by copy +/// or in place: how long it took, the calls made, and a hash of every result and of the operations +/// spent. The interpreter is made before the clock starts. +fn walk(data: &[u8], op: Op, seek: Option<&[u8]>, copy: bool) -> (Duration, usize, u64) { + let mut it = after(b""); + it.stack.push(Obj::Str(Shared::new(data.to_vec()))); + let mut calls = 0; + let mut h = DefaultHasher::new(); + let start = Instant::now(); + loop { + if let Some(seek) = seek { + it.stack.push(Obj::Str(Shared::new(seek.to_vec()))); + } + let r = if copy { by_copy(&mut it, op) } else { it.op(op) }; + assert_eq!(r, Ok(())); + calls += 1; + if !matches!(it.stack.pop(), Some(Obj::Bool(true))) { + break; + } + let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 }; + it.stack.iter().for_each(|o| mark(o, &mut h)); + it.stack.truncate(keep); + } + let took = start.elapsed(); + it.stack.iter().for_each(|o| mark(o, &mut h)); + it.ops_left().hash(&mut h); + it.release(); + (took, calls, h.finish()) +} + +/// Time both readers on `data` in 7 runs, alternating which goes first, check that they leave the +/// same, and print every run and the medians. +fn compare(what: &str, data: &[u8], op: Op, seek: Option<&[u8]>) { + let (mut old, mut new) = (vec![], vec![]); + let mut calls = 0; + for run in 0..7 { + let order: [bool; 2] = if run % 2 == 0 { [true, false] } else { [false, true] }; + let mut got = vec![]; + for copy in order { + let (took, n, last) = walk(data, op, seek, copy); + if copy { + old.push(took) + } else { + new.push(took) + } + calls = n; + got.push((n, last)); + } + assert!(got.first() == got.get(1), "{what}: the readers differ"); + } + let ms = |d: &Duration| format!("{:.2}", d.as_secs_f64() * 1000.0); + println!("{what}: {} bytes, {calls} calls", data.len()); + println!(" by copy, ms: {}", old.iter().map(ms).collect::>().join(" ")); + println!(" in place, ms: {}", new.iter().map(ms).collect::>().join(" ")); + let (o, w) = (median(&old), median(&new)); + println!(" median: by copy {} ms, in place {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9)); +} + +/// Times `token` and `search` walking a string by what each call leaves, against the copying +/// reference readers, in one process: strings of 4 KiB, 64 KiB and 512 KiB, of numbers and names +/// for `token` and of 128-byte lines for `search`. Run it in release: +/// `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn string_walks_timed() { + for kib in [4, 64, 512] { + let size = kib * 1024; + let mut words = Vec::with_capacity(size + 16); + let mut i = 0u32; + while words.len() < size { + let w = if i.is_multiple_of(2) { format!("{} ", i.wrapping_mul(2_654_435_761) % 100_000) } else { format!("/n{i} ") }; + words.extend_from_slice(w.as_bytes()); + i += 1; + } + compare(&format!("token, {kib} KiB"), &words, Op::Token, None); + let lines: Vec = (0..size / 128).flat_map(|i| format!("{:<127}\n", format!("line {i}")).into_bytes()).collect(); + compare(&format!("search, {kib} KiB"), &lines, Op::Search, Some(b"\n")); + } +} 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/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 76b9b71798..838015115b 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -355,6 +355,18 @@ pub fn circle_through(a: Point, b: Point, c: Point) -> Option<(Point, f64)> { (center.is_finite() && radius.is_finite()).then_some((center, radius)) } +/// The circle through two or three points: two are the ends of a diameter, and three lie on its +/// edge ([`circle_through`]). Its center and radius; `None` for any other number of points, for +/// points that are the same, for three on one line, and for a center or radius that is not finite. +pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { + let circle = match *points { + [a, b] if a != b => Some((a.midpoint(b), a.distance(b) / 2.0)), + [a, b, c] => circle_through(a, b, c), + _ => None, + }; + circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0) +} + /// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre. pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData { let n = sides.max(3); @@ -756,6 +768,19 @@ mod tests { assert_eq!(circle_through(a, b, Point::new(f64::NAN, 0.0)), None); } + /// Two points are the ends of a diameter, three are on the edge; one, four, two that are the + /// same and a point that is not finite give no circle. + #[test] + fn the_circle_through_two_or_three_points() { + let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN); + assert_eq!(circle_through_points(&[a, b]), Some((Point::new(4.0, 3.0), 5.0))); + let (center, r) = circle_through_points(&[a, b, c]).unwrap(); + assert!(center.distance(Point::new(4.0, 3.0)) < 1e-12 && (r - 5.0).abs() < 1e-12, "{center:?} {r}"); + for points in [&[a][..], &[a, b, c, a], &[a, a], &[a, Point::new(f64::INFINITY, 0.0)], &[], &[a, b, a.midpoint(b)]] { + assert_eq!(circle_through_points(points), None, "{points:?}"); + } + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. 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/headless.rs b/crates/mcp/src/headless.rs index cbd2e8ca87..db6c51d47d 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -53,7 +53,7 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ ( "tool.setOption", "Tool Option", - "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` reads them); kept options last across tool switches", + "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` or no params reads them; params that are not an object are an error); kept options last across tool switches", ), ]; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 7aba7acc78..870f4a23a3 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -17,6 +17,7 @@ mod limits; mod links; mod liquify; mod livepaint; +mod move_offsets; mod pen; mod persp; mod place; @@ -322,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() { @@ -1635,6 +1637,93 @@ fn doc_json(s: &mut Server) -> Value { serde_json::from_str(&text_of(&r)).unwrap() } +#[test] +fn transform_refused_by_a_later_operation_changes_nothing() { + let mut s = server(); + let count = |s: &mut Server| -> u64 { + let r = call(s, 90, "inspect_document", json!({})); + serde_json::from_str::(&text_of(&r)).unwrap()["objects"].as_u64().unwrap() + }; + let base = count(&mut s); + let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50}))); + let before = doc_json(&mut s); + for (id, args, says) in [ + (2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"), + (3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"), + (4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"), + (5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"), + (6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"), + ] { + let t = call(&mut s, id, "transform", args.clone()); + assert_eq!(t["isError"], true, "{args}: {t}"); + assert!(text_of(&t).contains(says), "{args}: {t}"); + assert_eq!(doc_json(&mut s), before, "{args}"); + } + // No undo step was recorded: one undo removes the rectangle. + assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false); + assert_eq!(count(&mut s), base, "one undo removes the rectangle"); +} + +#[test] +fn transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing() { + let inspect = |s: &mut Server, id| serde_json::from_str::(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap(); + let mut s = server(); + let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"}))); + let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"}))); + let before = inspect(&mut s, 3); + let cases = [ + ("object.reflect", json!({"dx": 10, "reflect": 42, "copy": true})), + ("object.reflect", json!({"dx": 10, "reflect": true})), + ("copy", json!({"dx": 10, "copy": "yes"})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": "center", "copy": true})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": [5]})), + ("origin", json!({"dx": 10, "rotate": 30, "origin": [5, "a"]})), + ]; + for (index, (says, mut args)) in cases.into_iter().enumerate() { + args["ids"] = json!([first]); + let request_id = 4 + index as u64 * 2; + let rejected = call(&mut s, request_id, "transform", args.clone()); + assert_eq!(rejected["isError"], true, "{args}: {rejected}"); + assert!(text_of(&rejected).contains(says), "{args}: {rejected}"); + // The document, the selection and the undo history are as they were. + assert_eq!(inspect(&mut s, request_id + 1), before, "{args}"); + } + // A null `reflect`, `copy` or `origin` is left out. + let applied = call(&mut s, 20, "transform", json!({"ids": [second], "dx": 10, "reflect": null, "copy": null, "origin": null})); + 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] +fn add_text_rejects_invalid_path_effects_before_editing() { + let mut s = server(); + let path = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M40 400 C150 300 250 500 360 400 Z"}))); + let before = call(&mut s, 2, "doc_inspect", json!({})); + for (args, message) in [ + (json!({"text": "Type", "path": path, "pathEffect": "not-an-effect"}), "not-an-effect"), + (json!({"text": "Type", "path": path, "pathEffect": 42}), "must be a string"), + (json!({"text": "Type", "path": path, "mode": "area", "pathEffect": "skew"}), "requires type on a path"), + (json!({"text": "Type", "x": 10, "y": 20, "pathEffect": "skew"}), "requires type on a path"), + ] { + let reply = call(&mut s, 3, "add_text", args); + assert_eq!(reply["isError"], true, "{reply}"); + assert!(text_of(&reply).contains(message), "{reply}"); + assert_eq!(call(&mut s, 4, "doc_inspect", json!({})), before, "path, selection and history must stay intact"); + } + let made = call(&mut s, 5, "add_text", json!({"text": "Type", "path": path, "pathEffect": "skew"})); + assert_eq!(made["isError"], false, "{made}"); + assert!(doc_json(&mut s).to_string().contains("\"pathEffect\":\"skew\"")); +} + #[test] fn text_effect_pathfinder_transform_graph_and_wrap_tools() { let mut s = server(); @@ -2210,3 +2299,55 @@ fn add_text_reports_overflow_and_takes_a_fit() { let point = made(&call(&mut s, 3, "add_text", json!({"text": "NEON DRIVE", "x": 0, "y": 300, "size": 60}))); assert!(point.get("overflow").is_none(), "{point}"); } + +#[test] +fn transform_rejects_nonnumeric_steps_before_editing() { + let inspect = |s: &mut Server, id| serde_json::from_str::(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap(); + let mut s = server(); + let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"}))); + let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"}))); + let before = inspect(&mut s, 3); + assert_eq!(before["selection"], json!([second])); + + let cases = [ + ("rotate", json!({"dx": 10, "rotate": "bad"})), + ("scale", json!({"dx": 10, "scale": "bad"})), + ("scaleX", json!({"dx": 10, "scaleX": "bad", "scaleY": 150})), + ("scaleY", json!({"dx": 10, "scaleX": 150, "scaleY": "bad"})), + ("shear", json!({"dx": 10, "shear": "bad"})), + ]; + for (index, (field, mut args)) in cases.into_iter().enumerate() { + args["ids"] = json!([first]); + let request_id = 4 + index as u64 * 2; + let rejected = call(&mut s, request_id, "transform", args); + assert_eq!(rejected["isError"], true, "{field}: {rejected}"); + assert!(text_of(&rejected).contains(field), "{field}: {rejected}"); + assert_eq!(inspect(&mut s, request_id + 1), before, "{field}"); + } + + let applied = call(&mut s, 14, "transform", json!({"ids": [first], "dx": 10, "rotate": null, "scale": 150, "scaleX": 125})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move", "scale"])); + let after = inspect(&mut s, 15); + assert_ne!(after, before); + assert_eq!(after["objects"], before["objects"]); + assert_eq!(after["selection"], json!([first])); + let bounds = &after["selectionBounds"]; + assert!((bounds["width"].as_f64().unwrap() - 25.0).abs() < 1e-6, "{bounds}"); + assert!((bounds["height"].as_f64().unwrap() - 22.5).abs() < 1e-6, "{bounds}"); + assert!(after["history"].as_array().unwrap().contains(&json!("Move"))); + assert!(after["history"].as_array().unwrap().contains(&json!("Scale"))); + + let applied = call(&mut s, 16, "transform", json!({"ids": [second], "dx": 10, "rotate": 90, "origin": [0, 0]})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move", "rotate"])); + let after = inspect(&mut s, 17); + assert_eq!(after["selection"], json!([second])); + let bounds = &after["selectionBounds"]; + for (field, expected) in [("x", 40.0), ("y", -70.0), ("width", 15.0), ("height", 20.0)] { + assert!((bounds[field].as_f64().unwrap() - expected).abs() < 1e-6, "{field}: {bounds}"); + } + assert!(after["history"].as_array().unwrap().ends_with(&[json!("Move"), json!("Rotate")])); +} diff --git a/crates/mcp/src/tests/liquify.rs b/crates/mcp/src/tests/liquify.rs index 4760380bc2..793f16efee 100644 --- a/crates/mcp/src/tests/liquify.rs +++ b/crates/mcp/src/tests/liquify.rs @@ -28,6 +28,36 @@ fn tool_options_are_set_headless_and_kept_across_tool_switches() { assert_eq!(command(&mut h, "tool.setOption", json!({}))["detail"], json!(6.0)); } +/// A value the tool refuses is an error result naming the tool and the option, and the options +/// stay as they were, the good value given with it included. +#[test] +fn a_refused_option_value_is_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for values in [json!({"width": 64, "detail": 99}), json!({"width": 64, "detail": "fine"})] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": {"values": values}})); + assert!(r.is_error, "{r:?}"); + assert!(format!("{:?}", r.content).contains("tool `warp`: `detail` must be a number from 1 to 10"), "{r:?}"); + } + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + +/// `tool.setOption` with params that are not an object is an error result that sets nothing; +/// without params it reads the options, as `{}` does. +#[test] +fn set_option_params_that_are_not_an_object_are_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for params in [json!(true), json!(7), json!([]), json!("x")] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": params})); + assert!(r.is_error, "{params}: {r:?}"); + } + assert_eq!(ok(&mut h, "run_command", json!({"command": "tool.setOption"})), before); + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + #[test] fn pointer_gestures_carry_pen_pressure() { let bloat = |pressure: f64| { diff --git a/crates/mcp/src/tests/move_offsets.rs b/crates/mcp/src/tests/move_offsets.rs new file mode 100644 index 0000000000..77fb8860a2 --- /dev/null +++ b/crates/mcp/src/tests/move_offsets.rs @@ -0,0 +1,67 @@ +use serde_json::{Value, json}; + +use super::{Server, call, id_of, server, text_of}; + +fn inspect(s: &mut Server, id: u64) -> Value { + serde_json::from_str(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap() +} + +fn path(s: &mut Server, id: u64, d: &str) -> u64 { + id_of(&call(s, id, "draw_path", json!({"d": d}))) +} + +fn child(doc: &Value, id: u64) -> Value { + doc["layers"][0]["children"].as_array().unwrap().iter().find(|node| node["id"] == id).unwrap().clone() +} + +#[test] +fn transform_rejects_malformed_move_offsets_before_selection_or_copy() { + let mut s = server(); + let first = path(&mut s, 1, "M40 40 L60 40 L60 60 L40 60 Z"); + let second = path(&mut s, 2, "M100 100 L130 100 L130 140 L100 140 Z"); + let before = inspect(&mut s, 3); + assert_eq!(before["selection"], json!([second])); + + let cases = [("dx", json!({"ids": [first], "dx": "bad", "copy": true})), ("dy", json!({"ids": [first], "dx": 10, "dy": "bad", "copy": true}))]; + for (index, (field, args)) in cases.into_iter().enumerate() { + let request_id = 4 + index as u64 * 2; + let result = call(&mut s, request_id, "transform", args); + assert_eq!(result["isError"], true, "{field}: {result}"); + assert!(text_of(&result).contains(field), "{field}: {result}"); + assert_eq!(inspect(&mut s, request_id + 1), before, "{field}"); + } + + // The recorded request omits dx and must still move a copy down by 10 points. + let result = call(&mut s, 8, "transform", json!({"ids": [first], "dy": 10, "copy": true})); + assert_eq!(result["isError"], false, "{result}"); + let reply: Value = serde_json::from_str(&text_of(&result)).unwrap(); + assert_eq!(reply["applied"], json!(["move"])); + let after = inspect(&mut s, 9); + let copied = after["selection"][0].as_u64().unwrap(); + assert_ne!(copied, first); + assert_ne!(copied, second); + let original_before = child(&before, first); + let original_after = child(&after, first); + let second_after = child(&after, second); + let copy_after = child(&after, copied); + assert_eq!(original_after["bounds"], original_before["bounds"]); + assert_eq!(second_after["bounds"], child(&before, second)["bounds"]); + assert_eq!(copy_after["bounds"]["x"], original_before["bounds"]["x"]); + assert_eq!(copy_after["bounds"]["y"], original_before["bounds"]["y"].as_f64().unwrap() + 10.0); + assert_eq!(copy_after["bounds"]["width"], original_before["bounds"]["width"]); + assert_eq!(copy_after["bounds"]["height"], original_before["bounds"]["height"]); + let before_history = before["history"].as_array().unwrap(); + let after_history = after["history"].as_array().unwrap(); + assert_eq!(after_history.len(), before_history.len() + 1); + assert_eq!(after_history.last(), Some(&json!("Move"))); + + // Null keeps the engine's optional-number default while a negative numeric offset is applied. + let result = call(&mut s, 10, "transform", json!({"ids": [second], "dx": null, "dy": -7})); + assert_eq!(result["isError"], false, "{result}"); + let after_null = inspect(&mut s, 11); + let moved = child(&after_null, second); + let second_before = child(&before, second); + assert_eq!(moved["bounds"]["x"], second_before["bounds"]["x"]); + assert_eq!(moved["bounds"]["y"], second_before["bounds"]["y"].as_f64().unwrap() - 7.0); + assert_eq!(after_null["history"].as_array().unwrap().last(), Some(&json!("Move"))); +} 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 1b86095c6e..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}) } @@ -466,20 +471,20 @@ pub fn tool_definitions() -> Vec { tool( "transform", "Transform", - "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.", + "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection center; `copy` transforms a copy. A scale, reflect or shear its command refuses, or an argument of the wrong type, returns that error before any step runs, and nothing changes.", 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/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 2ee9f01759..95c8e8671d 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -275,7 +275,15 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result j(transform(b, a)?), + "transform" => { + // Validate all numeric steps before the handler changes selection or runs a step. + for field in ["dx", "dy", "rotate", "scale", "scaleX", "scaleY", "shear"] { + if a.get(field).is_some_and(|value| !value.is_null() && value.as_f64().is_none()) { + return Err(format!("`{field}` must be a number")); + } + } + j(transform(b, a)?) + } "create_graph" => { let mut p = Value::Object(a.clone()); if p.get("type").is_none() { diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 717c641e19..cd7a0fc20b 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -247,6 +247,16 @@ pub(super) fn select_ids(b: &mut dyn Backend, a: &Args) -> Result<(), String> { pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { let text = a.get("text").and_then(Value::as_str).ok_or("missing string argument `text`")?; + // Creating type on a path replaces the path. Refuse an invalid effect before editing. + let path_effect = match a.get("pathEffect") { + None | Some(Value::Null) => None, + Some(Value::String(effect)) if vectorcraft_doc::PathEffect::parse(effect).is_some() => Some(effect), + Some(Value::String(effect)) => return Err(format!("unknown path effect `{effect}`")), + Some(_) => return Err("`pathEffect` must be a string".into()), + }; + if path_effect.is_some() && (!a.contains_key("path") || a.get("mode").is_some_and(|m| !matches!(m.as_str(), Some("onPath" | "path")))) { + return Err("`pathEffect` requires type on a path".into()); + } let mut style = json!({}); for k in ["size", "font", "color", "justify", "vertical"] { if let Some(v) = a.get(k) { @@ -276,12 +286,12 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } exec(b, "text.create", p)? }; - if let Some(e) = a.get("pathEffect").and_then(Value::as_str) { + if let Some(e) = path_effect { exec(b, "type.pathOptions", json!({"effect": e}))?; } let mut made = json!({"id": r.get("id")}); // A path effect is applied after the text is made: ask again how it fits then. - let overflow = match r.get("id").filter(|_| a.get("pathEffect").is_some()) { + let overflow = match r.get("id").filter(|_| path_effect.is_some()) { Some(id) => exec(b, "document.node", json!({"id": id, "summary": true}))?.get("overflow").and_then(Value::as_bool) == Some(true), None => r.get("overflow").is_some(), }; @@ -292,9 +302,42 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result { + // Each operation is its own command: check the params the later ones refuse before the first + // runs, so a refused request changes nothing. The `transform` arm of `dispatch` has already + // refused a `dx`, `dy`, `rotate`, `scale`, `scaleX`, `scaleY` or `shear` that is not a number. + fn bad(cmd: &'static str) -> impl Fn(String) -> String { + move |e| format!("invalid parameters for `{cmd}`: {e}") + } + let s = a.get("scale").and_then(Value::as_f64); + let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); + if sx.is_some() || sy.is_some() { + vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?; + } + // A null `reflect`, `copy` or `origin` is left out. + let reflect = match a.get("reflect") { + None | Some(Value::Null) => None, + Some(Value::String(axis)) => Some(axis.as_str()), + Some(v) => return Err(format!("invalid parameters for `object.reflect`: axis must be \"vertical\" or \"horizontal\", not `{v}`")), + }; + if let Some(axis) = reflect { + vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?; + } + let shear = a.get("shear").and_then(Value::as_f64); + if let Some(sh) = shear { + vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?; + } + let copy = match a.get("copy") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| format!("`copy` must be true or false, not {v}"))?, + }; + if let Some(o) = a.get("origin").filter(|o| !o.is_null()) + && !o.as_array().is_some_and(|xy| xy.len() == 2 && xy.iter().all(Value::is_number)) + { + return Err(format!("`origin` must be [x, y], not {o}")); + } select_ids(b, a)?; // With `copy`, the first operation duplicates and the rest transform the copy (the new selection). - let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false)); + let copy = std::cell::Cell::new(copy); let with = |mut p: Value| { if let Some(o) = a.get("origin") { p["origin"] = o.clone(); @@ -312,17 +355,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result exec(b, "object.rotate", with(json!({"angle": r})))?; done.push("rotate"); } - let s = a.get("scale").and_then(Value::as_f64); - let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); if sx.is_some() || sy.is_some() { exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?; done.push("scale"); } - if let Some(axis) = a.get("reflect").and_then(Value::as_str) { + if let Some(axis) = reflect { exec(b, "object.reflect", with(json!({"axis": axis})))?; done.push("reflect"); } - if let Some(sh) = a.get("shear").and_then(Value::as_f64) { + if let Some(sh) = shear { exec(b, "object.shear", with(json!({"angle": sh})))?; done.push("shear"); } diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 298bc426e5..88f60fd6c8 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -143,7 +143,18 @@ 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.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), + ( + "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…", + "", + "{path?, …document.export options}; no path: pick the file, then PNG Options with supplied options retained and defaults for omitted options", + ), ( "file.exportForScreens", "Export for Screens…", @@ -161,6 +172,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), + ( + "view.refreshMonitorProfile", + "Refresh Monitor Profile", + "", + "{} read the display's profile for Use Monitor Profile for Canvas (monitorProfileDisplay) again on the next frame, without waiting for the 10-second reading or the 1-second display check; while a reading runs, the request waits for it to end → {requested: true}, before the profile is read (ui.inspect › displayProfile reports the reading, and readRequested while it waits); an error while the preference is off, and where nothing reads the display's profile (the web build)", + ), ( "edit.autoSpellCheck", "Auto Spell Check", @@ -173,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", "", "{}"), ( @@ -188,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?}"), ( @@ -363,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", @@ -405,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", @@ -677,7 +729,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", @@ -846,7 +898,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( "tool.toggleTouchMode", @@ -860,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…", @@ -889,6 +946,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("help.about", "About VectorCraft", "", "{}"), ("help.checkForUpdates", "Check for Updates…", "", "{}"), ("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"), + ( + "help.discover", + "VectorCraft Help…", + "F1", + "{query?: string (at most 1024 characters, VectorCraft's limit)} show the Help panel without toggling it closed; a supplied query searches tools, menu commands, and built-in tutorials; omission keeps the current search. Returns {query, results: [{kind: tool|command|tutorial, id, label, path, shortcut}], selected: index|null}", + ), + ( + "help.discover.search", + "Search", + "", + "{query: string (at most 1024 characters, VectorCraft's limit)} search tools, menu commands, and built-in tutorials and show the Help panel; empty or whitespace-only text clears the results. Returns the help.discover result", + ), + ( + "help.discover.choose", + "Select", + "", + "{index: zero-based result index} show a tool's location, a tutorial's steps in Help, or a command's menu path and shortcut without running it; an invalid index is an error. Returns {result: chosen result, location: tool location, tutorial id, or command path}", + ), + ("help.discover.back", "Back", "", "{} return from a Help result to its search results without changing the query"), ( "help.safeMode", "Safe Mode…", @@ -942,7 +1018,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", @@ -996,13 +1072,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "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", @@ -1122,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", @@ -1170,6 +1252,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", @@ -1407,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", @@ -1484,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", @@ -1688,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 1ba560d05e..3f6dd8d5dd 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -1,6 +1,7 @@ //! Windows metafiles: hand-written EMF and WMF writers and readers. //! -//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile: +//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile, +//! and [`export_regions`] one metafile per region: //! //! - **EMF**: paths keep their Bézier curves, fills are solid brushes, strokes geometric pens with //! their width, caps, joins, miter limit and dashes; strokes a pen can't draw (aligned inside or @@ -81,20 +82,45 @@ pub struct Output { /// not); template layers, hidden objects and guides are left out. Raster effects should be turned /// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result { - let r = region.abs(); - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { + Ok(export_regions(doc, &[region], kind)?.pop().unwrap_or_default()) +} + +/// The error [`export_regions`] returns for `regions`, without writing anything: a region whose +/// corners are not all finite, or that has no width or no height, is empty. Corners in either +/// order are allowed. +pub fn check_regions(regions: &[Rect]) -> 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.is_empty() { + return Ok(Vec::new()); + } // The scene writes layers that do not print and leaves hidden layers and objects out. let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); - let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); - let bytes = match kind { - Kind::Emf => emf::write(&ops, r, doc.info_title()), - Kind::Wmf => wmf::write(&ops, r, &mut warnings), - }; - Ok(Output { bytes, warnings }) + let outputs = regions + .into_iter() + .map(|r| { + let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); + let bytes = match kind { + Kind::Emf => emf::write(&ops, r, doc.info_title()), + Kind::Wmf => wmf::write(&ops, r, &mut warnings), + }; + Output { bytes, warnings } + }) + .collect(); + Ok(outputs) } /// A metafile read into a document. diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 2314ccb637..658628f107 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -396,6 +396,177 @@ fn hidden_and_offboard_art_is_left_out() { assert!(export(&d, Rect::new(0.0, 0.0, 0.0, 10.0), Kind::Emf).is_err(), "an empty region"); } +/// One metafile of `doc` over `region`, applying the live effects for this region alone: what +/// [`export`] did for each region before [`export_regions`] applied them once for all regions. +fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result { + let r = region.abs(); + if ![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()); + } + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); + let doc = baked.as_ref().unwrap_or(doc); + let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run(); + let bytes = match kind { + Kind::Emf => crate::emf::write(&ops, r, doc.info_title()), + Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings), + }; + Ok(Output { bytes, warnings }) +} + +/// A Zig Zag effect with its default settings. +fn zig_zag() -> vectorcraft_doc::Effect { + vectorcraft_doc::Effect { id: "distort.zigZag".into(), params: Default::default(), visible: true } +} + +/// `boards` 100 pt squares side by side, each holding `paths` rectangles with a live Zig Zag +/// and a gradient-filled one, and every second one an instance of a symbol whose art has a Zig +/// Zag too; `boards` regions, one over each square. +fn zig_zag_boards(boards: usize, paths: usize) -> (Document, Vec) { + let mut d = Document::new(100.0 * boards as f64, 100.0); + let mut art = path(shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), blue(), red(), 1.0); + art.appearance.effects.push(zig_zag()); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Zig".into(), art: Arc::new(art) }); + let g = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + for b in 0..boards { + let x = 100.0 * b as f64; + for i in 0..paths { + let at = (i % 9) as f64 * 9.0; + let mut n = path(shapes::rectangle(Rect::new(x + at + 2.0, at + 2.0, x + at + 20.0, at + 15.0)), red(), blue(), 0.5); + n.appearance.effects.push(zig_zag()); + add(&mut d, n); + } + add(&mut d, path(shapes::rectangle(Rect::new(x + 60.0, 60.0, x + 90.0, 90.0)), g.clone(), Paint::None, 0.0)); + if b % 2 == 1 { + let inst = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Zig".into(), xf: Affine::translate((x + 50.0, 10.0)) }); + add(&mut d, inst); + } + } + let regions = (0..boards).map(|b| Rect::new(100.0 * b as f64, 0.0, 100.0 * (b + 1) as f64, 100.0)).collect(); + (d, regions) +} + +/// Each region's metafile is byte for byte, and warning for warning, what a separate export of +/// that region writes, in EMF and WMF, in the regions' order and in reverse. +#[test] +fn export_regions_writes_what_each_region_writes_alone() { + let (d, mut regions) = zig_zag_boards(3, 2); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + assert!(vectorcraft_effects::bake_document_placing_symbols(&d, true, layers).is_some(), "the document has live effects to apply"); + for _ in 0..2 { + for kind in [Kind::Emf, Kind::Wmf] { + let outs = export_regions(&d, ®ions, kind).unwrap(); + assert_eq!(outs.len(), regions.len()); + for (r, out) in regions.iter().zip(&outs) { + let alone = export_baking_each_region(&d, *r, kind).unwrap(); + assert!(out.bytes == alone.bytes, "{kind:?} over {r:?}: the bytes differ"); + assert_eq!(out.warnings, alone.warnings, "{kind:?} over {r:?}"); + let one = export(&d, *r, kind).unwrap(); + assert!(one.bytes == alone.bytes, "{kind:?} over {r:?}: export's bytes differ"); + assert_eq!(one.warnings, alone.warnings, "{kind:?} over {r:?}"); + } + if kind == Kind::Wmf { + assert!(outs.iter().all(|o| o.warnings.iter().any(|w| w.contains("gradients"))), "{:?}", outs[0].warnings); + } + } + regions.reverse(); + } +} + +/// An empty region among valid ones writes nothing and is the one error; no region writes no +/// metafile. +#[test] +fn export_regions_with_an_empty_region_writes_nothing() { + let (d, regions) = zig_zag_boards(2, 1); + for kind in [Kind::Emf, Kind::Wmf] { + for empty in [Rect::new(10.0, 10.0, 10.0, 50.0), Rect::new(0.0, 0.0, f64::NAN, 10.0), Rect::new(0.0, 0.0, f64::INFINITY, 10.0)] { + let with_empty = [regions[0], empty, regions[1]]; + assert_eq!(export_regions(&d, &with_empty, kind).map(|o| o.len()), Err("the export region is empty".to_string()), "{kind:?}"); + } + assert!(export_regions(&d, &[], kind).unwrap().is_empty(), "{kind:?}"); + // A region given right to left or bottom to top is the same region. + let flipped = Rect::new(regions[1].x1, regions[1].y1, regions[1].x0, regions[1].y0); + let outs = export_regions(&d, &[flipped], kind).unwrap(); + assert!(outs[0].bytes == export(&d, regions[1], kind).unwrap().bytes, "{kind:?}"); + } +} + +/// The CPU time all of this process's threads have used, from Linux's scheduler statistics; `None` +/// elsewhere. +fn process_cpu() -> Option { + let mut ns = 0u64; + for task in std::fs::read_dir("/proc/self/task").ok()? { + let stat = std::fs::read_to_string(task.ok()?.path().join("schedstat")).ok()?; + ns += stat.split_whitespace().next()?.parse::().ok()?; + } + Some(std::time::Duration::from_nanos(ns)) +} + +/// The time `f` takes: this process's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce() -> T) -> (std::time::Duration, T) { + match process_cpu() { + Some(before) => { + let t = f(); + (process_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)), t) + } + None => { + let start = std::time::Instant::now(); + let t = f(); + (start.elapsed(), t) + } + } +} + +/// Timings of an export of 1, 2 and 8 artboards that applies the live effects once for each +/// artboard and of [`export_regions`], which applies them once, in EMF and WMF: 500 rectangles with +/// a live Zig Zag on each artboard. The two take turns going first, 7 runs each, and every run's +/// files are compared. Ignored by default; it prints the median, fastest and slowest run and sets +/// no bound on them: +/// `cargo test --release -p vectorcraft-metafile --lib export_regions_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn export_regions_perf() { + const RUNS: usize = 7; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + eprintln!("export_regions_perf: {}", if process_cpu().is_some() { "process CPU time" } else { "wall clock" }); + eprintln!("export_regions_perf: {:>6} {:<4} {:>32} {:>32}", "boards", "kind", "bake per board ms (min-max)", "bake once ms (min-max)"); + for boards in [1, 2, 8] { + let (d, regions) = zig_zag_boards(boards, 500); + for kind in [Kind::Emf, Kind::Wmf] { + let each = || regions.iter().map(|r| export_baking_each_region(&d, *r, kind).unwrap()).collect::>(); + let once = || export_regions(&d, ®ions, kind).unwrap(); + let (mut old, mut new) = (Vec::new(), Vec::new()); + for run in 0..RUNS { + let ((to, a), (tn, b)) = if run % 2 == 0 { + let o = time(each); + (o, time(once)) + } else { + let n = time(once); + (time(each), n) + }; + old.push(to); + new.push(tn); + assert_eq!(a.len(), b.len()); + for (a, b) in a.iter().zip(&b) { + assert!(a.bytes == b.bytes && a.warnings == b.warnings, "{boards} boards, {kind:?}"); + } + } + old.sort(); + new.sort(); + eprintln!( + "export_regions_perf: {boards:>6} {:<4} {:>12.1} ({:>8.1}-{:>8.1}) {:>12.1} ({:>8.1}-{:>8.1})", + kind.id(), + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } + } +} + #[test] fn an_instance_whose_art_reaches_the_artboard_is_written() { // The symbol's red rectangle, (100, 100) to (140, 140), drawn from (-50, -50): on the artboard, diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index 87cc5ba56f..ed01ec3ce8 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,10 +4,12 @@ //! 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`]), 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; mod dashes; mod extend; @@ -25,6 +27,9 @@ use std::collections::BTreeSet; use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2}; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; +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 new file mode 100644 index 0000000000..f0afa31dc8 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -0,0 +1,827 @@ +//! 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; 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, FillRule, PathData, SubPath, shapes}; + +use crate::boolean::{DEFAULT_PRECISION, try_unite_all_with}; + +use super::Circle; + +/// How far (as a share of the radius) a path's outline may stray from a circle and still be read +/// as that circle. +const ROUND: f64 = 1e-3; +/// Points [`circle_of`] checks on each segment, its ends included. +const SAMPLES: usize = 9; + +/// Why [`smooth_bridge`] makes no outline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BridgeError { + /// One circle is inside the other (or they share a center). + Inside, + /// The circles are too far apart for the radius: the two arcs would not reach both circles, + /// or would cross before they do. + TooFar, + /// A radius or circle that is not a finite size above 0, or an outline too large for `f64`. + Bad, +} + +/// The circle `path` draws: one closed subpath whose outline stays within 0.1% of its radius of +/// a circle all the way around, once. `None` for any other path. +pub fn circle_of(path: &PathData) -> Option { + let [sp] = path.subpaths.as_slice() else { return None }; + if !sp.closed || sp.anchors.len() < 2 { + return None; + } + let b = path.bounds()?; + let (w, h) = (b.width(), b.height()); + if !(w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite()) || (w - h).abs() > ROUND * w.max(h) { + return None; + } + let (center, radius) = (b.center(), (w + h) / 4.0); + let off = |q: Point| (q.distance(center) - radius).abs() > ROUND * radius; + for k in 0..sp.segment_count() { + let seg = sp.segment(k); + if (0..SAMPLES).any(|i| off(seg.eval(i as f64 / (SAMPLES - 1) as f64))) { + return None; + } + } + // Around once: a path going around twice, or back on itself, encloses a different area. + let area = path.to_bezpath().area().abs(); + ((area - PI * radius * radius).abs() <= 4.0 * ROUND * area).then_some(Circle { center, radius }) +} + +/// The outline of circles `a` and `b` joined by two arcs of radius `radius` (pt), one on each +/// side of the line through their centers, each touching both circles from outside. The outline +/// runs around `a` on its side away from `b`, along one arc, around `b` on its side away from `a` +/// and back along the other arc; every anchor is smooth, as each arc and the circle it meets share +/// 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 { + return Err(BridgeError::Bad); + } + let axis = b.center - a.center; + // `f64::hypot`: `Vec2::hypot` squares the length, which overflows above about 1e154 pt. + let d = axis.x.hypot(axis.y); + if d + a.radius.min(b.radius) <= a.radius.max(b.radius) * (1.0 + 1e-9) { + return Err(BridgeError::Inside); + } + // The arcs' centers are `radius` outside both circles: where circles about the two centers, + // `radius` larger than each, cross. + let (ra, rb) = (radius + a.radius, radius + b.radius); + if !ra.is_finite() || !rb.is_finite() { + return Err(BridgeError::Bad); + } + // Halves and no squares, so no step overflows while the lengths fit in `f64`. + let half = ra / 2.0 + rb / 2.0; + if d / 2.0 > half { + return Err(BridgeError::TooFar); + } + let along = d / 2.0 + (ra - rb) / d * half; + let across = (ra - along).max(0.0).sqrt() * (ra / 2.0 + along / 2.0).max(0.0).sqrt() * SQRT_2; + if !along.is_finite() || !across.is_finite() { + return Err(BridgeError::Bad); + } + // Each arc runs between its points on `a` and `b`, which lie towards the two centers from the + // arc's center. Its point nearest the axis is the foot of its center on the axis when that foot + // is between the two centers, else one of its ends, which are off the axis. So the two arcs + // cross, leaving no neck, only when that foot is between the centers and nearer to the arc's + // center than its radius. + if along > 0.0 && along < d && across <= radius * (1.0 + 1e-9) { + return Err(BridgeError::TooFar); + } + let u = axis / d; + let n = Vec2::new(-u.y, u.x); + // Each side's arc center and where its arc touches `a` and `b`. + let side = |s: f64| { + let p = a.center + u * along + n * (s * across); + (p, a.center + (p - a.center) * (a.radius / ra), b.center + (p - b.center) * (b.radius / rb)) + }; + let ((p1, a1, b1), (p2, a2, b2)) = (side(1.0), side(-1.0)); + 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, + } + } +} + +/// 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 +/// on it): through the direction `through` from the center when given, else the shorter way. In +/// cubics of at most a quarter turn each, `from` exactly at the start and `to` at the end. +fn arc(out: &mut Vec, center: Point, r: f64, from: Point, to: Point, through: Option) { + let angle = |q: Vec2| q.y.atan2(q.x); + let start = angle(from - center); + // The turn from `from` to `to` counter-clockwise (in the y-up sense), 0 to 2π. + let ccw = (angle(to - center) - start).rem_euclid(TAU); + let sweep = match through { + Some(dir) if (angle(dir) - start).rem_euclid(TAU) <= ccw => ccw, + Some(_) => ccw - TAU, + None if ccw > PI => ccw - TAU, + None => ccw, + }; + let pieces = (sweep.abs() / FRAC_PI_2).ceil().max(1.0) as usize; + let step = sweep / pieces as f64; + // Handle length that makes a cubic follow the arc of `step`, signed with its direction. + let k = 4.0 / 3.0 * (step / 4.0).tan() * r; + let on = |t: f64| center + Vec2::new(t.cos(), t.sin()) * r; + let tangent = |t: f64| Vec2::new(-t.sin(), t.cos()); + for i in 0..pieces { + let (t0, t1) = (start + step * i as f64, start + step * (i + 1) as f64); + let p0 = if i == 0 { from } else { on(t0) }; + let p3 = if i + 1 == pieces { to } else { on(t1) }; + out.push(CubicBez::new(p0, p0 + tangent(t0) * k, p3 - tangent(t1) * k, p3)); + } +} + +#[cfg(test)] +mod tests { + use vectorcraft_geom::shapes; + + use super::*; + + fn circle(x: f64, y: f64, r: f64) -> Circle { + Circle { center: Point::new(x, y), radius: r } + } + + /// Every point the outline passes through, 32 to a segment. + fn outline(sp: &SubPath) -> Vec { + (0..sp.segment_count()).flat_map(|k| (0..32).map(move |i| sp.segment(k).eval(i as f64 / 32.0))).collect() + } + + /// The outline crosses the vertical line at `x` at these y values, top to bottom. + fn crossings_at(sp: &SubPath, x: f64) -> Vec { + let pts = outline(sp); + let mut ys: Vec = (0..pts.len()) + .filter_map(|i| { + let (p, q) = (pts[i], pts[(i + 1) % pts.len()]); + ((p.x - x) * (q.x - x) <= 0.0 && p.x != q.x).then(|| p.y + (q.y - p.y) * (x - p.x) / (q.x - p.x)) + }) + .collect(); + ys.sort_by(f64::total_cmp); + ys + } + + /// The bridge's width at `x`, from the outline's crossings there. + fn width_at(sp: &SubPath, x: f64) -> f64 { + let ys = crossings_at(sp, x); + ys.last().unwrap() - ys.first().unwrap() + } + + fn assert_smooth(sp: &SubPath) { + for a in sp.anchors.iter() { + let (i, o) = (a.p - a.h_in, a.h_out - a.p); + assert!(i.hypot() > 1e-6 && o.hypot() > 1e-6, "both handles at {a:?}"); + assert!(i.cross(o).abs() <= 1e-9 * i.hypot() * o.hypot() && i.dot(o) > 0.0, "the outline turns at {a:?}"); + assert_eq!(a.kind, AnchorKind::Smooth); + } + } + + /// Each point of the outline is on circle `c` or outside it. + fn outside(sp: &SubPath, c: Circle) -> bool { + outline(sp).iter().all(|p| p.distance(c.center) >= c.radius - 1e-3) + } + + #[test] + fn two_equal_circles_join_with_a_neck_narrower_than_the_circles() { + let (a, b) = (circle(0.0, 0.0, 20.0), circle(60.0, 0.0, 20.0)); + let sp = smooth_bridge(a, b, 20.0).unwrap(); + assert!(sp.closed); + assert_smooth(&sp); + // The arcs' centers are 40 from each circle's center: (30, ±√700), so the neck at x = 30 is + // 2 × (√700 − 20) wide. + let neck = 2.0 * (700f64.sqrt() - 20.0); + assert!((width_at(&sp, 30.0) - neck).abs() < 1e-2, "{}", width_at(&sp, 30.0)); + assert!(width_at(&sp, 30.0) < width_at(&sp, 10.0)); + // Around each circle on its far side, and symmetric. + let ys = crossings_at(&sp, -10.0); + assert!((ys[0] + 300f64.sqrt()).abs() < 1e-2 && (ys[1] - 300f64.sqrt()).abs() < 1e-2, "{ys:?}"); + assert!((width_at(&sp, 50.0) - width_at(&sp, 10.0)).abs() < 1e-2); + let b = PathData::single(sp).bounds().unwrap(); + // Within the cubics' own error from a true circle (about 0.03% of the radius). + assert!((b.x0 + 20.0).abs() < 1e-2 && (b.x1 - 80.0).abs() < 1e-2 && (b.y1 - 20.0).abs() < 1e-2, "{b:?}"); + } + + #[test] + fn the_arcs_touch_both_circles_and_run_on_from_them() { + for (a, b, r) in [ + (circle(0.0, 0.0, 20.0), circle(60.0, 0.0, 20.0), 20.0), + (circle(10.0, 5.0, 30.0), circle(70.0, 40.0, 8.0), 40.0), + (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 15.0), 10.0), + ] { + let sp = smooth_bridge(a, b, r).unwrap(); + assert_smooth(&sp); + // The outline goes around the outside of both circles, never into either. + assert!(outside(&sp, a) && outside(&sp, b)); + // On each circle the outline leaves along the circle's tangent, where an arc takes over + // as well: two anchors on each circle are where an arc meets it. + for c in [a, b] { + let on: Vec<_> = sp.anchors.iter().filter(|q| (q.p.distance(c.center) - c.radius).abs() < 1e-6).collect(); + assert!(on.len() >= 2, "{}", on.len()); + for q in on { + let radial = q.p - c.center; + assert!(radial.dot(q.h_out - q.p).abs() <= 1e-6 * radial.hypot() * (q.h_out - q.p).hypot(), "{q:?}"); + } + } + assert!(sp.anchors.len() <= 12, "{}", sp.anchors.len()); + // Every segment off the two circles is part of an arc of radius `r` that touches both + // circles from outside: its center is `r` farther than each circle's radius from it. + let on = |q: Point, c: Circle| (q.distance(c.center) - c.radius).abs() < 1e-3; + let mut arcs = 0; + for k in 0..sp.segment_count() { + let seg = sp.segment(k); + let (p0, pm, p1) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0)); + if on(pm, a) || on(pm, b) { + continue; + } + arcs += 1; + let (center, radius) = circumcircle(p0, pm, p1); + assert!((radius - r).abs() < 1e-2 * r, "radius {radius} for {r}"); + assert!((center.distance(a.center) - (r + a.radius)).abs() < 1e-2 * r, "touches {a:?}"); + assert!((center.distance(b.center) - (r + b.radius)).abs() < 1e-2 * r, "touches {b:?}"); + } + assert!((2..=4).contains(&arcs), "{arcs}"); + } + } + + /// The circle through three points: its center and radius. + fn circumcircle(p: Point, q: Point, s: Point) -> (Point, f64) { + let d = 2.0 * (p.x * (q.y - s.y) + q.x * (s.y - p.y) + s.x * (p.y - q.y)); + let sq = |v: Point| v.x * v.x + v.y * v.y; + let x = (sq(p) * (q.y - s.y) + sq(q) * (s.y - p.y) + sq(s) * (p.y - q.y)) / d; + let y = (sq(p) * (s.x - q.x) + sq(q) * (p.x - s.x) + sq(s) * (q.x - p.x)) / d; + let c = Point::new(x, y); + (c, c.distance(p)) + } + + #[test] + fn unequal_circles_join_round_both() { + let (a, b) = (circle(0.0, 0.0, 30.0), circle(70.0, 0.0, 10.0)); + let sp = smooth_bridge(a, b, 40.0).unwrap(); + assert_smooth(&sp); + let bounds = PathData::single(sp.clone()).bounds().unwrap(); + assert!((bounds.x0 + 30.0).abs() < 1e-2 && (bounds.x1 - 80.0).abs() < 1e-2 && (bounds.y0 + 30.0).abs() < 1e-2, "{bounds:?}"); + // The neck narrows from the big circle towards the small one. + assert!(width_at(&sp, 35.0) > width_at(&sp, 50.0)); + assert!(width_at(&sp, 50.0) < 20.0); + } + + #[test] + fn unequal_circles_join_at_large_radii_overlapping_or_not() { + // With a large radius the arcs' centers lie beyond the smaller circle, so the arcs never + // reach the axis even though their centers are nearer to it than their radius. + for (a, b, r) in [ + (circle(0.0, 0.0, 10.0), circle(25.0, 0.0, 30.0), 100.0), + (circle(0.0, 0.0, 30.0), circle(25.0, 0.0, 10.0), 30.0), + (circle(0.0, 0.0, 30.0), circle(25.0, 0.0, 10.0), 50.0), + (circle(0.0, 0.0, 30.0), circle(60.0, 0.0, 8.0), 300.0), + ] { + let sp = smooth_bridge(a, b, r).unwrap_or_else(|e| panic!("{a:?} {b:?} {r}: {e:?}")); + assert_smooth(&sp); + assert!(outside(&sp, a) && outside(&sp, b)); + // The outline crosses the axis only at the two far ends: it does not cross itself. + let pts = outline(&sp); + let crossings = (0..pts.len()).filter(|&i| (pts[i].y > 0.0) != (pts[(i + 1) % pts.len()].y > 0.0)).count(); + assert_eq!(crossings, 2, "{a:?} {b:?} {r}"); + // It encloses more than the larger circle. + let area = PathData::single(sp).to_bezpath().area().abs(); + assert!(area > PI * a.radius.max(b.radius).powi(2), "{area}"); + } + } + + #[test] + fn overlapping_and_touching_circles_are_joined() { + let (a, b) = (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 20.0)); + let sp = smooth_bridge(a, b, 10.0).unwrap(); + assert_smooth(&sp); + // The circles cross at x = 15, y = ±√175; the bridge fills in the notch there. + assert!(width_at(&sp, 15.0) > 2.0 * 175f64.sqrt()); + assert!(width_at(&sp, 15.0) < 40.0); + let touching = smooth_bridge(circle(0.0, 0.0, 20.0), circle(40.0, 0.0, 20.0), 10.0).unwrap(); + assert_smooth(&touching); + assert!(width_at(&touching, 20.0) > 1.0); + } + + #[test] + fn far_apart_circles_and_nested_ones_make_no_bridge() { + let (a, b) = (circle(0.0, 0.0, 10.0), circle(100.0, 0.0, 10.0)); + assert_eq!(smooth_bridge(a, b, 5.0), Err(BridgeError::TooFar), "arcs don't reach"); + // The arcs reach both circles (gap 80 < 2 × 45) but cross before they do. + assert_eq!(smooth_bridge(a, b, 45.0), Err(BridgeError::TooFar), "no neck left"); + // A large enough radius bridges them: the neck stays open above (d/2)² − r² over 2r = 120. + assert!(smooth_bridge(a, b, 130.0).is_ok()); + assert_eq!(smooth_bridge(circle(0.0, 0.0, 30.0), circle(5.0, 0.0, 10.0), 10.0), Err(BridgeError::Inside)); + assert_eq!(smooth_bridge(circle(0.0, 0.0, 30.0), circle(0.0, 0.0, 30.0), 10.0), Err(BridgeError::Inside)); + assert_eq!(smooth_bridge(a, b, 0.0), Err(BridgeError::Bad)); + assert_eq!(smooth_bridge(a, b, f64::NAN), Err(BridgeError::Bad)); + 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. + let (a, b) = (circle(0.0, 0.0, 5e153), circle(1.5e154, 0.0, 5e153)); + let sp = smooth_bridge(a, b, 5e153).unwrap(); + assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); + assert_smooth(&sp); + // The two radius sums fit in f64, but not their total. + let (a, b) = (circle(-5e307, 0.0, 1e307), circle(5e307, 0.0, 1e307)); + let sp = smooth_bridge(a, b, 1.5e308).unwrap(); + assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); + // The arcs' centers would lie beyond the largest f64. + let (a, b) = (circle(0.0, 0.0, 1e308), circle(1.5e308, 0.0, 1e308)); + assert_eq!(smooth_bridge(a, b, 1e308), Err(BridgeError::Bad)); + } + + #[test] + fn circles_are_told_from_other_paths() { + let round = shapes::ellipse(kurbo::Rect::new(10.0, 20.0, 50.0, 60.0)); + let c = circle_of(&round).unwrap(); + assert!(c.center.distance(Point::new(30.0, 40.0)) < 1e-9 && (c.radius - 20.0).abs() < 1e-9); + let oval = shapes::ellipse(kurbo::Rect::new(0.0, 0.0, 50.0, 40.0)); + assert_eq!(circle_of(&oval), None); + let square = PathData::single(SubPath::polyline(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true)); + assert_eq!(circle_of(&square), None); + let mut open = round.clone(); + open.subpaths[0].closed = false; + assert_eq!(circle_of(&open), None); + let two = PathData::new(vec![round.subpaths[0].clone(), round.subpaths[0].clone()]); + assert_eq!(circle_of(&two), None); + } +} diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index a42e628cad..655e84e311 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -8,6 +8,9 @@ //! Both are found as roots over the normal's angle: sampled, then refined by bisection, with //! sampled minima refined too so that a double root (outlines that touch) or two roots between //! neighboring samples are kept. +//! +//! One of the two may be a point instead ([`Outline::point`]): its support value is `p · n`, and +//! the tangents are the lines through it that touch the other outline. use std::f64::consts::TAU; @@ -60,7 +63,7 @@ pub enum OutlineError { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Coincide; -/// A convex closed outline that [`common_tangents`] takes. +/// A convex closed outline, or a point, that [`common_tangents`] takes. #[derive(Clone, Debug)] pub enum Outline { /// The unit circle under an affine map: the center is the map's translation, `m` its linear @@ -70,9 +73,19 @@ pub enum Outline { /// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then /// comes later in the list as the angle of `n` grows. Convex { segments: Vec, center: Point, size: f64, ccw: bool }, + /// A single point. + Point { at: Point }, } impl Outline { + /// The point `at`, whose tangents are the lines through it. + pub fn point(at: Point) -> Result { + if !at.x.is_finite() || !at.y.is_finite() { + return Err(OutlineError::Empty); + } + Ok(Outline::Point { at }) + } + /// The ellipse that `unit` maps the unit circle onto. pub fn ellipse(unit: Affine) -> Result { let [a, b, c, d, e, f] = unit.as_coeffs(); @@ -183,6 +196,7 @@ impl Outline { size: *size, ccw: *ccw, }, + Outline::Point { at } => Outline::Point { at: *at + d }, } } @@ -203,7 +217,7 @@ impl Outline { /// The support value at `n` and the segment it is reached on, from every segment. fn support_scan(&self, n: Vec2) -> (f64, usize) { match self { - Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Ellipse { .. } | Outline::Point { .. } => (self.support(n), 0), Outline::Convex { segments, .. } => { let mut best = (f64::MIN, 0); for (i, s) in segments.iter().enumerate() { @@ -222,7 +236,7 @@ impl Outline { /// where the support value was reached at a normal angle a little less than `n`'s. fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) { match self { - Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Ellipse { .. } | Outline::Point { .. } => (self.support(n), 0), Outline::Convex { segments, ccw, .. } => { let len = segments.len(); if len == 0 { @@ -251,14 +265,20 @@ impl Outline { } } - /// The center: an ellipse's, or a path's center of area. + /// The center: an ellipse's, a path's center of area, or the point itself. pub fn center(&self) -> Point { match self { Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center, + Outline::Point { at } => *at, } } - /// The diagonal of the bounds (an ellipse's: of the box its axes span). + /// Whether this is a point. + pub fn is_point(&self) -> bool { + matches!(self, Outline::Point { .. }) + } + + /// The diagonal of the bounds (an ellipse's: of the box its axes span; a point's: 0). pub fn size(&self) -> f64 { match self { Outline::Ellipse { m, .. } => { @@ -266,6 +286,7 @@ impl Outline { 2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt() } Outline::Convex { size, .. } => *size, + Outline::Point { .. } => 0.0, } } @@ -280,6 +301,7 @@ impl Outline { } best } + Outline::Point { at } => at.to_vec2().dot(n), } } @@ -320,6 +342,7 @@ impl Outline { let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() } + Outline::Point { at } => vec![*at], } } } @@ -406,7 +429,14 @@ fn dir(angle: f64) -> Vec2 { /// the angle of its normal. Separate outlines have two of each; overlapping ones only external /// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the /// other none; outlines that touch share one tangent where they touch. +/// +/// When one of them is a point, its external and internal tangents are the same lines, and they +/// come back as external ones: two when the point lies outside the other outline, one when it lies +/// on it, none inside. Two points have none. pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincide> { + if a.is_point() && b.is_point() { + return Ok(vec![]); + } // Worked out about the point between the two centers. let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0; let (a, b) = (&a.shifted(-origin), &b.shifted(-origin)); @@ -434,7 +464,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincid let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0)); let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; - let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let internal = if a.is_point() || b.is_point() { + vec![] + } else { + roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)? + }; let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb }); let mut out = Vec::with_capacity(external.len() + internal.len()); for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { @@ -506,8 +540,13 @@ fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: boo // A double root's angle is found less exactly than a simple one's, so touching points may // stand a little apart. let (from, to) = if double && hi - lo <= 1e-6 * size { - // Touching at one point: the narrower outline's width along the line, centered there. - let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min); + // Touching at one point: the narrower outline's width along the line, centered there. A + // point on the other outline takes that outline's width. + let width = [a, b] + .into_iter() + .filter(|o| !o.o.is_point()) + .map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0) + .fold(f64::MAX, f64::min); let mid = (lo + hi) / 2.0; (mid - width / 2.0, mid + width / 2.0) } else if mean(&on_a) <= mean(&on_b) { @@ -975,6 +1014,127 @@ mod tests { assert!((best - 0.25).abs() < 1e-12, "{best}"); } + #[test] + fn a_point_outside_a_turned_ellipse_has_two_tangents_through_it() { + let m = ellipse_map(100.0, 50.0, 40.0, 15.0, 30.0); + let (oval, p) = (Outline::ellipse(m).unwrap(), Point::new(-60.0, 120.0)); + let samples = sample_ellipse(m, 5_000); + for point_first in [true, false] { + let point = Outline::point(p).unwrap(); + let all = if point_first { common_tangents(&point, &oval) } else { common_tangents(&oval, &point) }.unwrap(); + assert_eq!(all.len(), 2, "{all:?}"); + for t in &all { + assert_eq!(t.kind, TangentKind::External); + // Each runs from the first outline given to the second: from the point when it + // comes first. + let (at_point, on_oval) = if point_first { (t.from, t.to) } else { (t.to, t.from) }; + assert!((at_point - p).hypot() < 1e-9, "{t:?}"); + // Taken back to the unit circle, the far end lies on it and the line runs square to + // its radius there. + let inv = m.inverse(); + let (q, d) = ((inv * on_oval).to_vec2(), (inv * on_oval) - (inv * at_point)); + assert!((q.hypot() - 1.0).abs() < 1e-9, "{q:?}"); + assert!((q.dot(d) / d.hypot()).abs() < 1e-7, "{q:?} {d:?}"); + // The whole ellipse lies on one side of the line. + let dir = on_oval - at_point; + let n = Vec2::new(-dir.y, dir.x) / dir.hypot(); + let side: Vec = samples.iter().map(|s| (*s - at_point).dot(n)).collect(); + let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!(lo > -1e-6 || hi < 1e-6, "crosses: {lo} .. {hi}"); + } + } + } + + #[test] + fn a_point_on_inside_and_beside_a_path() { + // On a circle: the one tangent there, centered on the point and as long as the circle is + // wide. + let on = common_tangents(&Outline::point(Point::new(10.0, 0.0)).unwrap(), &circle(0.0, 0.0, 10.0)).unwrap(); + assert_eq!(on.len(), 1, "{on:?}"); + assert!(ends_within(&on[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{on:?}"); + // Inside, and two points: none. + assert!(common_tangents(&Outline::point(Point::new(3.0, 4.0)).unwrap(), &circle(0.0, 0.0, 10.0)).unwrap().is_empty()); + let two = (Outline::point(Point::new(0.0, 0.0)).unwrap(), Outline::point(Point::new(5.0, 0.0)).unwrap()); + assert!(common_tangents(&two.0, &two.1).unwrap().is_empty()); + // Beside a square, in line with its bottom side: that tangent covers the whole side, and + // the other one touches the corner at (10, 10). + let square = SubPath::polyline(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(Point::from), true); + let sq = Outline::convex(&square).unwrap(); + let p = Point::new(20.0, 0.0); + let all = common_tangents(&Outline::point(p).unwrap(), &sq).unwrap(); + assert_eq!(all.len(), 2, "{all:?}"); + assert!(all.iter().any(|t| ends_at(t, p, Point::new(0.0, 0.0))), "{all:?}"); + assert!(all.iter().any(|t| ends_at(t, p, Point::new(10.0, 10.0))), "{all:?}"); + assert!(all.iter().all(|t| (t.from - p).hypot() < 1e-9), "from the point: {all:?}"); + // On a straight side, off its middle: the one tangent is that side, covered whole. + let side = common_tangents(&Outline::point(Point::new(2.0, 0.0)).unwrap(), &sq).unwrap(); + assert_eq!(side.len(), 1, "{side:?}"); + assert!(ends_at(&side[0], Point::new(0.0, 0.0), Point::new(10.0, 0.0)), "{side:?}"); + // At a corner of the square: one line through the corner, at the middle of the directions + // that touch there, as long as the square is wide along it. + let corner = common_tangents(&Outline::point(Point::new(10.0, 10.0)).unwrap(), &sq).unwrap(); + assert_eq!(corner.len(), 1, "{corner:?}"); + // The diagonal is 10√2 long, so each end lies 5√2 from the corner, along (1, -1). + assert!(ends_within(&corner[0], Point::new(15.0, 5.0), Point::new(5.0, 15.0), 1e-5), "{corner:?}"); + // A point that is not finite is refused. + assert_eq!(Outline::point(Point::new(f64::NAN, 0.0)).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::point(Point::new(0.0, f64::INFINITY)).err(), Some(OutlineError::Empty)); + } + + #[test] + fn a_point_placed_on_a_turned_outline_has_one_tangent() { + // A point worked out on the outline lies a rounding error inside or outside it, and still + // gets the one line there, as long as the outline is wide along it. + let one = |p: Point, o: &Outline, samples: &[Point]| { + let all = common_tangents(&Outline::point(p).unwrap(), o).unwrap(); + assert_eq!(all.len(), 1, "{p:?}: {all:?}"); + // The line runs through the point. + let (a, d) = (all[0].from, all[0].to - all[0].from); + assert!(d.hypot() > 1.0 && ((p - a).cross(d) / d.hypot()).abs() < 1e-6, "{p:?}: {all:?}"); + // Its length is the outline's width along it, measured on dense samples. + let u = d / d.hypot(); + let (lo, hi) = samples.iter().map(|s| s.to_vec2().dot(u)).fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(v), hi.max(v))); + assert!((d.hypot() - (hi - lo)).abs() < 1e-3, "{p:?}: {} against {}", d.hypot(), hi - lo); + }; + let m = ellipse_map(100.0, 50.0, 40.0, 15.0, 30.0); + let (oval, oval_samples) = (Outline::ellipse(m).unwrap(), sample_ellipse(m, 20_000)); + for k in 0..37 { + let a = 0.17 + k as f64 * TAU / 37.0; + one(m * Point::new(a.cos(), a.sin()), &oval, &oval_samples); + } + // A closed Bézier circle, turned and moved: on each anchor and partway along each segment. + let turned = shapes::ellipse(Rect::new(-60.0, -60.0, 60.0, 60.0)).transformed(Affine::translate((37.3, -12.9)) * Affine::rotate(0.7)); + let sp = turned.subpaths[0].clone(); + let (path, path_samples) = (Outline::convex(&sp).unwrap(), sample_path(&sp, 5_000)); + for an in sp.anchors.iter() { + one(an.p, &path, &path_samples); + } + for k in 0..sp.segment_count() { + for t in [0.21, 0.5, 0.83] { + one(sp.segment(k).eval(t), &path, &path_samples); + } + } + } + + #[test] + fn a_point_within_the_touching_tolerance_counts_as_on_the_outline() { + // The tolerance is a billionth of the larger of the circle's size and the point's distance + // from its center: closer than that, inside or outside, the point gets the one line there. + let round = circle(0.0, 0.0, 10.0); + let tol = 1e-9 * round.size().max(10.0); + let at = |dx: f64| common_tangents(&Outline::point(Point::new(10.0 + dx, 0.0)).unwrap(), &round).unwrap(); + for dx in [-0.5 * tol, 0.5 * tol] { + let on = at(dx); + assert_eq!(on.len(), 1, "{dx}: {on:?}"); + assert!(ends_within(&on[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{dx}: {on:?}"); + } + // Farther than that, a point inside gets none and a point outside gets two. + assert!(at(-100.0 * tol).is_empty()); + assert_eq!(at(100.0 * tol).len(), 2); + assert!(at(-1e-6).is_empty()); + assert_eq!(at(1e-6).len(), 2); + } + #[test] fn open_concave_empty_and_identical_outlines_are_refused() { let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false); diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index a8dd48628c..2fccfb393c 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash "; /// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it /// keeps every offset. const PLACEHOLDER: &str = "0000000000000000"; -/// Deepest name tree searched for the editing file. -const MAX_DEPTH: usize = 16; +/// The most name tree nodes searched for the editing file. +const MAX_NODES: usize = 1 << 16; /// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -77,12 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option { editing_in(&crate::pages::open(bytes, password).ok()?) } +/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]). +struct Search<'a> { + /// The editing file's file specification, if one was found. + spec: Option>, + /// A name tree key searched names the editing file (set also when its file specification + /// can't be read). + keyed: bool, + /// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched. + cut: bool, +} + +/// The search of a parsed PDF's attachments for the editing file. +fn editing_file_spec(pdf: &Pdf) -> Search<'_> { + let xref = pdf.xref(); + let Some(tree) = xref + .get::>(xref.root_id()) + .and_then(|catalog| catalog.get::>(b"Names")) + .and_then(|names| names.get::>(b"EmbeddedFiles")) + else { + return Search { spec: None, keyed: false, cut: false }; + }; + let (mut keyed, mut cut) = (false, false); + let spec = editing_spec(tree, &mut keyed, &mut cut, xref); + Search { spec, keyed, cut } +} + +/// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't +/// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be +/// resolved)? Also true when the name tree is too large to search to its end. +pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool { + let search = editing_file_spec(pdf); + search.spec.is_some() || search.keyed || search.cut +} + +/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`] +/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it +/// reads. +pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool { + editing_file_spec(pdf).cut +} + /// [`editing`] of a parsed PDF. pub(crate) fn editing_in(pdf: &Pdf) -> Option { - let xref = pdf.xref(); - let catalog = xref.get::>(xref.root_id())?; - let tree = catalog.get::>(b"Names")?.get::>(b"EmbeddedFiles")?; - let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?; + let spec = editing_file_spec(pdf).spec?; let files = spec.get::>(b"EF")?; let stream = files.get::>(b"F").or_else(|| files.get::>(b"UF"))?; let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default(); @@ -96,10 +134,59 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { Some(Editing { data, intact }) } -/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect -/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, xref: &'a XRef) -> Option> { +/// The first file specification of the editing file in the name tree `tree`, searched in order at +/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the +/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is +/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is +/// set when a key searched names the editing file, and `cut` when nodes are left unsearched. +fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option> { + let mut seen = HashSet::::new(); + let mut nodes = vec![tree]; + let mut found = None; + // Nodes still to be searched, counting the ones waiting in `nodes`. + let mut left = MAX_NODES - 1; + while let Some(node) = nodes.pop() { + // Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut. + if found.is_none() { + found = node_spec(&node, keyed, xref); + } + let Some(kids) = node.get::>(b"Kids") else { continue }; + // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The + // reference is checked before the kid is read, so a shared kid is read once. + let mut kids: Vec> = items(&kids) + .filter_map(|raw| match raw { + MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into()), + MaybeRef::NotRef(Object::Dict(kid)) => Some(kid), + _ => None, + }) + .take(left.saturating_add(1)) + .collect(); + if kids.len() > left { + *cut = true; + kids.truncate(left); + } + left -= kids.len(); + nodes.extend(kids.into_iter().rev()); + } + found +} + +/// The file specification of the editing file among the name tree node `node`'s own `Names`. +/// `keyed` is set when a key names the editing file. +fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { + // The keys read as written, so a value that can't be resolved doesn't shift the pairs. + let mut raw = items(&names); + while let (Some(key), Some(_)) = (raw.next(), raw.next()) { + let key = match key { + MaybeRef::NotRef(Object::String(key)) => Some(key), + MaybeRef::Ref(r) => xref.get::>(r.into()), + MaybeRef::NotRef(_) => None, + }; + if key.is_some_and(|key| is_editing_name(&key)) { + *keyed = true; + } + } let mut items = names.iter::>(); while let (Some(_), Some(spec)) = (items.next(), items.next()) { if let Object::Dict(spec) = spec @@ -109,29 +196,19 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet= MAX_DEPTH { - return None; - } - let kids = node.get::>(b"Kids")?; - // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The - // reference is checked before the kid is read, so a shared kid is read once. - items(&kids).find_map(|raw| { - let kid = match raw { - MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into())?, - MaybeRef::NotRef(Object::Dict(kid)) => kid, - _ => return None, - }; - editing_spec(&kid, depth + 1, seen, xref) - }) + None } /// A file specification naming the editing file (current or legacy name), in any text string /// encoding. fn is_editing_file(spec: &Dict<'_>) -> bool { - [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| { - let name = text_string(name.as_bytes()); - name == EDITING_FILE || name == LEGACY_EDITING_FILE - }) + [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| is_editing_name(&name)) +} + +/// A text string that is the editing file's name (current or legacy), in any encoding. +fn is_editing_name(name: &PdfString<'_>) -> bool { + let name = text_string(name.as_bytes()); + name == EDITING_FILE || name == LEGACY_EDITING_FILE } /// The most decoded page content [`page_hash`] reads in all (bytes). diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index e11cda9acd..bd241421c7 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -64,14 +64,16 @@ pub(crate) struct Sheet<'a> { impl Writer { /// A PDF with `set`'s version, standard, compression and colour output, and `doc`'s metadata - /// under `title`, created at `created` (Unix seconds). With `cmyk`, transparency blends in - /// CMYK (unless the colours are converted to RGB). + /// and language under `title`, created at `created` (Unix seconds). With `cmyk`, transparency + /// blends in CMYK (unless the colours are converted to RGB). pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option, cmyk: bool) -> Result { let out = ColorOut::new(doc, set)?; let mut warnings = out.profile_notes.clone(); - // Tagged CMYK colours need the profile (PDF/A tags every colour). - let cmyk_profile = if out.tagged { out.cmyk_icc() } else { None }; - if out.tagged && cmyk_profile.is_none() { + // Tagged CMYK colours need the profile (PDF/A tags every colour). When CMYK colors are + // DeviceCMYK (`device_cmyk`), the writer gets no CMYK profile. + let tags_cmyk = out.tagged && !out.device_cmyk(); + let cmyk_profile = if tags_cmyk { out.cmyk_icc() } else { None }; + if tags_cmyk && cmyk_profile.is_none() { warnings.push(format!("the CMYK profile {} can't be embedded: CMYK colours are written untagged", out.cmyk_profile())); } let version = match set.compatibility { @@ -109,7 +111,11 @@ impl Writer { created: created.map(date_time), modified: None, }; - let pdf = write::Writer::new(settings, metadata); + // The document language (Document Setup) as the catalog's `Lang` and the XMP packet's + // `dc:language` (ISO 32000-1, 14.9.2): its BCP 47 tag. A language without a tag writes + // none rather than a guess. + let language = vectorcraft_doc::setup::language_tag(&doc.setup.language).map(str::to_string); + let pdf = write::Writer::new_with_language(settings, metadata, language); Ok(Self { pdf, cmyk: out.blends_cmyk(cmyk), @@ -271,8 +277,15 @@ impl Writer { PdfError::from(e) })?; if self.cmyk { - let profile = self.out.tagged.then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); - cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), self.out.standard != Standard::PdfA2b); + let device = self.out.device_cmyk(); + let profile = (self.out.tagged && !device).then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); + let without = match (&profile, self.out.standard != Standard::PdfA2b) { + _ if device => Without::AlwaysDeviceCmyk, + (None, _) => Without::FirstCmyk, + (Some(_), true) => Without::DeviceCmyk, + (Some(_), false) => Without::Rgb, + }; + cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), without); } let lab = !self.lab_spots.is_empty() && !self.out.standard.cmyk_only(); let bytes = if lab { crate::lab_spot::lab_alternates(bytes, &self.lab_spots) } else { bytes }; @@ -287,19 +300,12 @@ impl Writer { /// are rewritten in place to DeviceCMYK (or the CMYK profile's space), keeping their length so the /// cross-reference offsets stay valid. Luminosity masks' groups keep RGB: mask luminance is that /// of screen colours, as on screen. Tagged groups blend in the space of CMYK profile `profile` -/// (the one that tags CMYK colours) when the file has one. When its only CMYK spaces are of other -/// profiles (images' own), they blend in DeviceCMYK where `device` allows it, else they keep RGB; -/// without `profile`, they blend in the first CMYK space. -fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: bool) { +/// (the one that tags CMYK colours) when the file has one; otherwise they blend as `without` says. +fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, without: Without) { let masks = luminosity_mask_groups(pdf); let mut spaces = vec![("/CS/DeviceRGB".to_string(), "/CS/DeviceCMYK".to_string())]; if tagged { let own = profile.and_then(|icc| crate::output::tagging_stream(pdf, &crate::patch::Xref::read(pdf)?, icc)); - let without = match (profile, device) { - (None, _) => Without::FirstCmyk, - (Some(_), true) => Without::DeviceCmyk, - (Some(_), false) => Without::Rgb, - }; spaces.extend(icc_spaces(pdf, own, without)); } let mut from = 0; @@ -316,11 +322,15 @@ fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: b /// What tagged groups blend in when the file holds no space of the document's CMYK profile. #[derive(Clone, Copy, Debug, PartialEq)] enum Without { - /// The first ICC-based CMYK space of the file. + /// The first ICC-based CMYK space of the file (the document's profile isn't known). FirstCmyk, + /// DeviceCMYK when the file has an ICC-based CMYK space (images' own profiles), outside PDF/A. DeviceCmyk, - /// The RGB space they have. + /// The RGB space they have (PDF/A, which allows no DeviceCMYK next to images' own profiles). Rgb, + /// DeviceCMYK, also when the file has no ICC-based CMYK space: CMYK colors are DeviceCMYK + /// ([`crate::output::ColorOut::device_cmyk`]). + AlwaysDeviceCmyk, } /// The ICC-based RGB colour spaces of `pdf`, each with the ICC-based CMYK one to blend in instead, @@ -352,6 +362,7 @@ fn icc_spaces(pdf: &[u8], own: Option, without: Without) -> Vec<(String, St Without::FirstCmyk => cmyk, Without::DeviceCmyk => cmyk.map(|_| "/CS/DeviceCMYK".to_string()), Without::Rgb => None, + Without::AlwaysDeviceCmyk => Some("/CS/DeviceCMYK".to_string()), }); let Some(cmyk) = cmyk else { return vec![] }; rgb.into_iter().map(|r| (r, cmyk.clone())).collect() @@ -435,6 +446,11 @@ mod tests { // profile's space; the first CMYK space when the document's profile isn't known. assert_eq!(icc_spaces(SPACES, None, Without::DeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); assert_eq!(icc_spaces(SPACES, None, Without::Rgb), []); - assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb, "/CS 2 0 R".to_string())]); + assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb.clone(), "/CS 2 0 R".to_string())]); + // CMYK colors written as DeviceCMYK: groups blend there, with or without a CMYK ICC space. + assert_eq!(icc_spaces(SPACES, None, Without::AlwaysDeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); + let rgb_only = b"%PDF-1.7\n1 0 obj\n[/ICCBased 4 0 R]\nendobj\n4 0 obj\n<>stream\n\nendstream\nendobj\n"; + assert_eq!(icc_spaces(rgb_only, None, Without::DeviceCmyk), []); + assert_eq!(icc_spaces(rgb_only, None, Without::AlwaysDeviceCmyk), [(rgb, "/CS/DeviceCMYK".to_string())]); } } 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 a9cd9ada7c..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,12 +63,16 @@ 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(), image_keys: HashMap::new(), raster_scales: HashMap::new(), cmyk_keys: HashSet::new(), + intent_cmyk: None, separation_paints: HashMap::new(), opaque: HashSet::new(), warnings: vec![], @@ -118,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(); @@ -419,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; @@ -449,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; @@ -879,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 { @@ -1149,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 @@ -1162,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); @@ -1183,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 45ca7f7081..47924a717d 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -1,4 +1,4 @@ -use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; +use super::entry::{INTENT_KEY, INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; use super::state::{ Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline, stroke_layer, stroke_outline, @@ -242,8 +242,11 @@ impl<'a> Device<'a> for Builder<'_> { match image { Image::Raster(r) => { let white = self.white_images; + // A DeviceCMYK image takes the output intent's profile only where no DefaultCMYK + // replaces DeviceCMYK, so it is cached apart from the same image drawn where one does. + let intent = !white && self.intent_cmyk.is_some() && self.scan.cmyk_defaults.get(&r.stream().dict().obj_id()) == Some(&false); // Inside an alpha mask the same image is read again, white (its own cache key). - let key = craft_pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 }; + let key = craft_pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let st = r.stream(); let (w, h) = (r.width(), r.height()); // CMYK images keep their samples (read once per image). @@ -251,7 +254,8 @@ impl<'a> Device<'a> for Builder<'_> { let cmyk = if known || white { None } else { - crate::import_image::cmyk(st, w, h).unwrap_or_else(|why| { + let intent = self.intent_cmyk.as_deref().filter(|_| intent); + crate::import_image::cmyk(st, w, h, intent).unwrap_or_else(|why| { self.warn(why); None }) @@ -449,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/entry.rs b/crates/pdf/src/import/entry.rs index 8f84b9a332..5b945c6b25 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -9,6 +9,9 @@ use super::{ /// Mixed into an image's cache key when it is read white inside an alpha soft mask. pub(super) const WHITE_KEY: u128 = 0x7717_e000_a1fa; +/// Mixed into an image's cache key when a DeviceCMYK image there takes the output intent's profile. +pub(super) const INTENT_KEY: u128 = 0x1e7e_0c3c_0b5a; + /// The name of the paths text imports as. pub(super) const TEXT_OUTLINES: &str = ""; @@ -281,6 +284,7 @@ fn read_opened( b.unsure = route && ocgs.list.iter().any(|g| (all_on && !g.on) || !g.print); b.taken = taken; b.warnings = notes; + b.intent_cmyk = crate::import_image::output_intent_cmyk(pdf); b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data); let cache = InterpreterCache::new(); let mut x = 0.0; diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index ba0c23a808..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, @@ -103,6 +134,9 @@ pub(super) struct Builder<'p> { pub(super) raster_scales: HashMap, /// The images kept with their CMYK samples ([`crate::import_image`]). pub(super) cmyk_keys: HashSet, + /// The file's PDF/X output intent profile of CMYK, which DeviceCMYK images are tagged with + /// ([`crate::import_image::output_intent_cmyk`]). + pub(super) intent_cmyk: Option>, /// Images in a Separation space, by key: the paint of their ink, or `None` when they open in /// RGB (an ink that can't be told, tints that can't be read). pub(super) separation_paints: HashMap>, diff --git a/crates/pdf/src/import_image.rs b/crates/pdf/src/import_image.rs index cafae6d448..ecab9e6e08 100644 --- a/crates/pdf/src/import_image.rs +++ b/crates/pdf/src/import_image.rs @@ -5,15 +5,17 @@ //! ([`ImageBlob::cmyk_tiff`]). An ICC-based image keeps the CMYK profile its color space holds //! ([`icc_profile`]): the TIFF carries it, and a kept JPEG carries it in place of its own //! ([`jpeg_with_icc`]), or, when its segments can't hold it, is stored as a CMYK TIFF carrying it. +//! In a file with a PDF/X output intent of CMYK, a DeviceCMYK image keeps that intent's profile +//! the same way ([`output_intent_cmyk`]), since the intent describes DeviceCMYK there. //! A mask (`/SMask`, `/Mask`) doesn't change that: the importer //! carries it as the image's opacity mask ([`has_mask`]). A DeviceN image of process plates only //! keeps them the same way, as a CMYK image ([`process_devicen`]). An image of one ink (a //! Separation, or a DeviceN of one colorant) keeps it: its tints are read as a grayscale image //! ([`tint_gray`]) that the ink colorizes. Every other image is read as RGB by the interpreter. -use craft_pdf::syntax::Filter; use craft_pdf::syntax::object::stream::{ImageColorSpace, ImageDecodeParams}; use craft_pdf::syntax::object::{Array, Dict, Name, Stream}; +use craft_pdf::syntax::{Filter, Pdf}; use vectorcraft_doc::ImageBlob; use vectorcraft_doc::cmyk::{Inks, MAX_CMYK_PIXELS, jpeg_components, jpeg_with_icc}; @@ -55,7 +57,11 @@ fn icc_profile(d: &Dict<'_>) -> Option> { if it.next::>()?.as_ref() != b"ICCBased" { return None; } - let s = it.next::>()?; + cmyk_profile(&it.next::>()?) +} + +/// The four-component CMYK profile stream `s` holds, when an image can be tagged with it. +fn cmyk_profile(s: &Stream<'_>) -> Option> { if s.dict().get::(b"N") != Some(4) { return None; } @@ -64,6 +70,23 @@ fn icc_profile(d: &Dict<'_>) -> Option> { valid_icc(&icc, *b"CMYK").then(|| icc.into_owned()) } +/// The CMYK profile of the catalog's PDF/X output intent (`/S /GTS_PDFX` with a four-component +/// `DestOutputProfile`), which DeviceCMYK colors are in. `None` without one. +pub(crate) fn output_intent_cmyk(pdf: &Pdf) -> Option> { + let xref = pdf.xref(); + let intents = xref.get::>(xref.root_id())?.get::>(b"OutputIntents")?; + let pdfx = intents.iter::>().take(MAX_INTENTS).find(|i| i.get::>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX"))?; + cmyk_profile(&pdfx.get::>(b"DestOutputProfile")?) +} + +/// The output intents read before giving up on finding the PDF/X one. +const MAX_INTENTS: usize = 16; + +/// Is the image's color space DeviceCMYK (or its inline abbreviation)? +fn device_cmyk(d: &Dict<'_>) -> bool { + d.get::>(key(d, b"ColorSpace", b"CS")).is_some_and(|n| matches!(n.as_ref(), b"DeviceCMYK" | b"CMYK")) +} + /// Each component's Decode range (`[0 1]` each when the array is missing or malformed). fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { let mut out = [(0.0, 1.0); 4]; @@ -78,14 +101,15 @@ fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { } /// The image `st` (`width` × `height` pixels) in CMYK: `Ok(None)` when it isn't a CMYK image, -/// `Err` (a warning) when it is one that is read as RGB. -pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result, &'static str> { +/// `Err` (a warning) when it is one that is read as RGB. `intent` is the file's PDF/X output intent +/// profile of CMYK ([`output_intent_cmyk`]), which a DeviceCMYK image is tagged with. +pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32, intent: Option<&[u8]>) -> Result, &'static str> { let d = st.dict(); if !cmyk_space(d) { return process_devicen(st, width, height); } let ranges = decode_ranges(d); - let icc = icc_profile(d); + let icc = icc_profile(d).or_else(|| intent.filter(|_| device_cmyk(d)).map(<[u8]>::to_vec)); let filters = st.filters(); if ranges == INVERTED && matches!(filters.as_slice(), [Filter::DctDecode]) { let raw = st.raw_data(); diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index b65254eafa..7f2e9cc161 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -280,6 +280,10 @@ pub(crate) struct Scan { /// Something overprints with overprint mode 0, where a `DeviceCMYK` colour's zero components /// knock out; the document's overprint is the nonzero one (mode 1). pub zero_mode: bool, + /// The images the page draws (image XObjects by object, inline images as `None`), each with + /// whether it is drawn where a `/DefaultCMYK` is in scope, which replaces DeviceCMYK there + /// (ISO 32000-2 §8.6.5.6). An image drawn both ways is `true`. + pub cmyk_defaults: HashMap, bool>, /// The colorant names of the Separation and DeviceN spaces the page sets (`cs`, `CS`), and of /// those of the shading patterns it sets (`scn`, `SCN`) and of the shadings it draws (`sh`), /// each once (none when the page uses more than [`MAX_INKS`] inks or changes ink more than @@ -663,53 +667,23 @@ impl Walker<'_, '_> { self.out.type3_cache_map.insert(hash, (f_key, to_unicode)); } } - let is_colour = if is_type3 { - let mut colour = false; - let mut seen_streams = HashSet::new(); - let mut decoded_bytes = 0usize; - const MAX_CHARPROC_BYTES: usize = 16 << 20; - if let Some(char_procs) = f.get::>(b"CharProcs") { - for key in char_procs.keys() { - if let Some(stream) = char_procs.get::>(key.as_ref()) { - if !seen_streams.insert(stream.cache_key()) { - continue; - } - if decoded_bytes >= MAX_CHARPROC_BYTES { - colour = true; - break; - } - if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { - decoded_bytes = decoded_bytes.saturating_add(data.len()); - let mut iter = TypedIter::new(data.as_ref()); - while let Some(op) = iter.next() { - match op { - TypedInstruction::ColorGlyph(_) => { - colour = true; - break; - } - TypedInstruction::ShapeGlyph(_) => break, - _ => {} - } - } - if colour { - break; - } - } - } - } - } - colour - } else { - false - }; + // A font is noted once for the document, so its glyph procedures are read only the + // first time any page or form lists it. self.fonts.entry(f_key).or_insert_with(|| { let embedded = embeds_glyphs(&f); + let is_colour = is_type3 && sets_glyph_colors(&f); FontNote { name, embedded, vertical: vertical_metrics(&f, embedded), is_type3, to_unicode, is_colour } }); } } } + /// An image drawn with `res` in scope, as the interpreter looks up its `/DefaultCMYK`. + fn drawn_image(&mut self, id: Option, res: &Resources<'_>) { + let default = res.get_color_space(&Name::new_unescaped(b"DefaultCMYK")).is_some(); + *self.out.cmyk_defaults.entry(id).or_default() |= default; + } + fn walk(&mut self, data: &[u8], res: &Resources<'_>, depth: u32) { let mut iter = TypedIter::new(data); self.note_fonts(res); @@ -874,12 +848,17 @@ impl Walker<'_, '_> { | TypedInstruction::ShowTexts(_) | TypedInstruction::NextLineAndShowText(_) | TypedInstruction::ShowTextWithParameters(_) => self.shown(), + TypedInstruction::InlineImage(_) => self.drawn_image(None, res), TypedInstruction::XObject(x) => { if !self.is_visible() { continue; } let Some(s) = res.get_x_object(x.0) else { continue }; let d = s.dict(); + if d.get::>(b"Subtype").as_deref() == Some(b"Image") { + self.drawn_image(d.obj_id(), res); + continue; + } if d.get::>(b"Subtype").as_deref() != Some(b"Form") || d.get::<[f32; 4]>(b"BBox").is_none() { continue; } @@ -1108,6 +1087,48 @@ fn font_name(f: &Dict<'_>) -> Option { Some(stripped.unwrap_or(base)) } +/// The most bytes of a Type 3 font's glyph procedures decoded to look for colored glyphs. +const MAX_CHARPROC_BYTES: usize = 16 << 20; + +// The glyph procedures decoded by `sets_glyph_colors` on this thread. +#[cfg(test)] +thread_local! { + pub(crate) static TEST_CHARPROC_DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether Type 3 font `f` has a glyph procedure that sets its own color (`d0`, ISO 32000-1 +/// §9.6.5): its procedures are read until one starts with `d0`, each up to its `d0` or `d1`. Past +/// [`MAX_CHARPROC_BYTES`] of them the font is taken to have one. +fn sets_glyph_colors(f: &Dict<'_>) -> bool { + let Some(char_procs) = f.get::>(b"CharProcs") else { return false }; + let mut seen_streams = HashSet::new(); + let mut decoded_bytes = 0usize; + for key in char_procs.keys() { + if let Some(stream) = char_procs.get::>(key.as_ref()) { + if !seen_streams.insert(stream.cache_key()) { + continue; + } + if decoded_bytes >= MAX_CHARPROC_BYTES { + return true; + } + #[cfg(test)] + TEST_CHARPROC_DECODES.with(|n| n.set(n.get() + 1)); + if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { + decoded_bytes = decoded_bytes.saturating_add(data.len()); + let mut iter = TypedIter::new(data.as_ref()); + while let Some(op) = iter.next() { + match op { + TypedInstruction::ColorGlyph(_) => return true, + TypedInstruction::ShapeGlyph(_) => break, + _ => {} + } + } + } + } + } + false +} + /// Whether font `f` carries its own glyphs: a font program in its descriptor (a composite font's in /// its descendant's), or a Type 3 font's glyph procedures. A font that doesn't is drawn with a /// stand-in, whose glyphs say nothing about which installed face the document means. 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/output.rs b/crates/pdf/src/output.rs index f5e4bb6e36..83104215c2 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -25,12 +25,17 @@ //! document's), RGB with sRGB (colours of another RGB space as their sRGB equivalents) and grey //! with the sRGB tone curve. Otherwise they are device colours. PDF/A, PDF/X-3 and PDF/X-4 //! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a -//! CMYK destination (see [`crate::pdfx`]). A CMYK image that keeps its numbers is tagged with -//! the CMYK profile it carries, if any, with `all` and `taggedSource`, and in PDF/A, PDF/X-3 -//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). When +//! CMYK destination (see [`crate::pdfx`]). In PDF/X-3 and PDF/X-4, CMYK colors in the profile +//! of a CMYK output intent are DeviceCMYK, and so are all CMYK colors with `none`, unless +//! colors are converted to a CMYK destination of another profile ([`ColorOut::device_cmyk`]). +//! A CMYK image that keeps +//! its numbers is tagged with the CMYK profile it carries, if any, with `all` and +//! `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination` +//! ([`ColorOut::cmyk_image_icc`]); not when that profile is a DeviceCMYK output intent's. When //! `profiles` isn't set, colors are written as with `none` and gray and RGB images keep the //! profiles they carry (but in PDF/X-1a); when it is set to `none`, no image keeps its own -//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4 +//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4, +//! where CMYK images lose theirs only when CMYK colors are DeviceCMYK //! ([`ColorOut::source_profiles`]). //! - Output intent: the profile `outputIntent` names, embedded as the `/GTS_PDFX` output intent //! of the catalog with the condition, identifier and registry; Trapped goes in the document @@ -82,6 +87,13 @@ pub(crate) struct ColorOut { no_profiles: bool, /// The CMYK profile that tags CMYK colours. cmyk_profile: String, + /// CMYK colors are written as DeviceCMYK although colors are tagged + /// ([`Self::device_cmyk`]): the profile of the CMYK output intent they are in, embedded once + /// as its `DestOutputProfile`. + device_icc: Option>, + /// With [`Self::device_icc`], CMYK images are untagged too, whatever profile they carry + /// (`profiles` is `none`). + untag_cmyk_images: bool, /// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB /// space isn't sRGB. pub srgb_note: Option, @@ -132,6 +144,8 @@ impl Default for ColorOut { image_icc: false, no_profiles: false, cmyk_profile, + device_icc: None, + untag_cmyk_images: false, srgb_note: None, pixels: OnceLock::new(), tagged_pixels: OnceLock::new(), @@ -290,9 +304,32 @@ impl ColorOut { } out.catalog = catalog(set, &out.cmyk_profile); out.standard = set.standard; + // In PDF/X-3 and PDF/X-4 the CMYK output intent characterizes DeviceCMYK: CMYK colors in + // its profile are written as DeviceCMYK, and with `none` every CMYK color is, unless + // colors are converted to a CMYK destination of another profile. Files without a standard + // keep the tags that `profiles` asks for. + let intent_cmyk = out.catalog.as_ref().and_then(|c| c.intent.as_ref()?.profile.as_ref()).filter(|(_, n)| *n == 4); + let none = set.output.profiles == Some(ProfileInclusion::None); + let to_cmyk = out.dest.as_ref().is_some_and(|d| d.model == Model::Cmyk); + if out.tagged + && set.standard.is_pdfx() + && let Some(intent) = intent_cmyk.and_then(|(name, _)| cms::icc_bytes(name).ok()) + && ((none && !to_cmyk) || cms::icc_bytes(&out.cmyk_profile).is_ok_and(|own| own == intent)) + { + out.device_icc = Some(intent); + out.untag_cmyk_images = none; + } Ok(out) } + /// CMYK colors are written as DeviceCMYK although colors are tagged, in PDF/X-3 and PDF/X-4 + /// with a CMYK output intent: its profile is the one they are in, or `profiles` is `none` and + /// there is no CMYK destination of another profile. RGB and gray colors stay tagged, and + /// so does a CMYK image that carries another profile, except with `none`. + pub(crate) fn device_cmyk(&self) -> bool { + self.device_icc.is_some() + } + /// Transparency blends in CMYK: converting to CMYK, or (without conversion) in a CMYK /// document (`cmyk`). pub(crate) fn blends_cmyk(&self, cmyk: bool) -> bool { @@ -415,22 +452,29 @@ impl ColorOut { /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it /// carries, when its numbers are kept and the Profiles setting or the standard includes source - /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. + /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. When CMYK + /// colors are DeviceCMYK ([`Self::device_cmyk`]), an image that carries the output intent's + /// profile is untagged too, and so is every CMYK image with `none`. pub(crate) fn cmyk_image_icc(&self, blob: &vectorcraft_doc::ImageBlob) -> Option> { if !self.image_icc || self.cmyk_pixels().is_some() { return None; } - crate::images::cmyk_icc(blob) + let icc = crate::images::cmyk_icc(blob)?; + match &self.device_icc { + Some(intent) if self.untag_cmyk_images || icc == **intent => None, + _ => Some(icc), + } } /// How CMYK image `blob` is tagged ([`crate::images::recode_cmyk`]): with the profile /// [`Self::cmyk_image_icc`] gives (`icc`), else untagged, without a JPEG's own `ICC_PROFILE` - /// segments when Don't Include Profiles was set. + /// segments when Don't Include Profiles was set or CMYK colors are DeviceCMYK + /// ([`Self::device_cmyk`]). pub(crate) fn cmyk_tag<'a>(&self, icc: Option<&'a [u8]>) -> crate::images::CmykTag<'a> { use crate::images::CmykTag; match icc { Some(icc) => CmykTag::Profile(icc), - None if self.no_profiles => CmykTag::Removed, + None if self.no_profiles || self.device_cmyk() => CmykTag::Removed, None => CmykTag::Untagged, } } diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 470432aa8f..ec593baf24 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -261,6 +261,18 @@ impl Opened { crate::editing::editing_in(&self.pdf) } + /// Does the PDF list the editing file among its attachments, also when + /// [`editing`](Self::editing) can't read it? + pub fn has_editing_file(&self) -> bool { + crate::editing::has_editing_file_in(&self.pdf) + } + + /// Is the PDF's attachment name tree too large to search to its end? It may then list an + /// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads. + pub fn editing_search_cut(&self) -> bool { + crate::editing::editing_search_cut_in(&self.pdf) + } + /// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it. pub fn illustrator_data(&self) -> Option> { private_data(&self.pdf) diff --git a/crates/pdf/src/patch.rs b/crates/pdf/src/patch.rs index 8b9d69b908..9235f22cea 100644 --- a/crates/pdf/src/patch.rs +++ b/crates/pdf/src/patch.rs @@ -107,6 +107,42 @@ impl Xref { /// A replacement of bytes `start..end` of the file. type Edit = (usize, usize, Vec); +/// Where byte offsets of the old file land in the new one, for edits sorted by start that do not +/// overlap, whose ends therefore never decrease. +struct Moves { + /// Each edit's end, in order. + ends: Vec, + /// The change in length made by the edits up to and including each one. + shifts: Vec, +} + +impl Moves { + /// `None` when a change in length doesn't fit an `isize`. + fn new(edits: &[Edit]) -> Option { + let mut total: isize = 0; + let mut shifts = Vec::with_capacity(edits.len()); + for (start, end, new) in edits { + let removed = isize::try_from(end.checked_sub(*start)?).ok()?; + total = total.checked_add(isize::try_from(new.len()).ok()?)?.checked_sub(removed)?; + shifts.push(total); + } + Some(Self { ends: edits.iter().map(|e| e.1).collect(), shifts }) + } + + /// Where `off` lands: moved by every edit that ends at or before it. + fn at(&self, off: usize) -> Option { + match self.ends.partition_point(|&end| end <= off) { + 0 => Some(off), + n => off.checked_add_signed(*self.shifts.get(n - 1)?), + } + } +} + +/// `off` as the ten digits of a cross-reference entry; `None` past what ten digits hold. +fn entry_offset(off: usize) -> Option { + (u64::try_from(off).ok()? < 10_000_000_000).then(|| format!("{off:010}")) +} + /// The edits of one PDF, applied together by [`Self::apply`]. pub(crate) struct Patch { edits: Vec, @@ -139,18 +175,17 @@ impl Patch { } /// `pdf` with the edits, new objects and trailer entries, and a cross-reference table that - /// matches. Refused when an edit overlaps another or reaches past the objects. + /// matches. Refused when an edit overlaps another or reaches past the objects, or when an + /// object would start past the ten digits a cross-reference entry gives its offset in. pub fn apply(mut self, pdf: &[u8], xref: &Xref) -> Result, PdfError> { let bad = |why: &str| PdfError::Write(format!("can't edit the written PDF: {why}")); self.edits.sort_by_key(|e| (e.0, e.1)); if self.edits.windows(2).any(|w| w[0].1 > w[1].0) || self.edits.iter().any(|e| e.0 > e.1 || e.1 > xref.at) { return Err(bad("edits overlap")); } - // Where a byte offset of the old file lands in the new one. let edits = &self.edits; - let moved = |off: usize| -> usize { - edits.iter().filter(|e| e.1 <= off).fold(off as isize, |o, e| o + e.2.len() as isize - (e.1 - e.0) as isize) as usize - }; + let moves = Moves::new(edits).ok_or_else(|| bad("edits too large"))?; + let too_far = || bad("an object lies past what the cross-reference table holds"); let added: usize = self.edits.iter().map(|e| e.2.len()).sum::() + self.objects.iter().map(|o| o.len() + 32).sum::(); let mut out = Vec::with_capacity(pdf.len() + added + 64); let mut at = 0; @@ -175,7 +210,7 @@ impl Patch { for e in old.chunks(20) { match number(e, 0) { Some((off, _)) if e.get(17) == Some(&b'n') => { - out.extend_from_slice(format!("{:010}", moved(off)).as_bytes()); + out.extend_from_slice(moves.at(off).and_then(entry_offset).ok_or_else(too_far)?.as_bytes()); out.extend_from_slice(e.get(10..).unwrap_or_default()); } _ => out.extend_from_slice(e), @@ -183,7 +218,8 @@ impl Patch { } let eol = old.get(18..20).unwrap_or(b"\r\n"); for off in offsets { - out.extend_from_slice(format!("{off:010} 00000 n").as_bytes()); + out.extend_from_slice(entry_offset(off).ok_or_else(too_far)?.as_bytes()); + out.extend_from_slice(b" 00000 n"); out.extend_from_slice(eol); } // The trailer, with its size and the new entries. @@ -201,3 +237,279 @@ impl Patch { Ok(out) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + /// A PDF written as the export writes one: objects `<< /N n >>` numbered from 1, those `free` + /// picks left out with a free entry, then one cross-reference table and the trailer. + fn written(count: usize, free: impl Fn(usize) -> bool) -> Vec { + let mut pdf = b"%PDF-1.7\n".to_vec(); + let mut entries = b"0000000000 65535 f\r\n".to_vec(); + for n in 1..=count { + if free(n) { + entries.extend_from_slice(b"0000000000 00001 f\r\n"); + continue; + } + entries.extend(format!("{:010} 00000 n\r\n", pdf.len()).bytes()); + pdf.extend(format!("{n} 0 obj\n<< /N {n} >>\nendobj\n").bytes()); + } + let at = pdf.len(); + pdf.extend(format!("xref\n0 {}\n", count + 1).bytes()); + pdf.extend(entries); + pdf.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{at}\n%%EOF", count + 1).bytes()); + pdf + } + + /// A small linear congruential generator, so every run makes the same edits. + struct Rng(u64); + + impl Rng { + /// A number in `0..n` (0 when `n` is 0). + fn below(&mut self, n: usize) -> usize { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + usize::try_from(self.0 >> 33).unwrap() % n.max(1) + } + + fn bytes(&mut self) -> Vec { + (0..self.below(9)).map(|i| b'a' + u8::try_from(i).unwrap()).collect() + } + } + + /// About `wanted` edits that don't overlap, in shuffled order, at random places among the + /// objects and at object starts: replacements that grow, shrink or remove bytes, edits that end + /// at an object's start, and inserts, several of them at one place. None when `wanted` is 0. + fn edits(pdf: &[u8], xref: &Xref, rng: &mut Rng, wanted: usize) -> Vec { + if wanted == 0 { + return vec![]; + } + let first = b"%PDF-1.7\n".len(); + let mut points: Vec = xref.objects(pdf).into_iter().map(|(_, off)| off).collect(); + points.extend((0..wanted).map(|_| first + rng.below(xref.at() - first + 1))); + points.push(xref.at()); + points.sort_unstable(); + points.dedup(); + let mut out = vec![]; + for w in points.windows(2) { + let (p, q) = (w[0], w[1]); + match rng.below(6) { + 0 => {} + 1 => out.push((p, q, rng.bytes())), + 2 => out.push((p, p, rng.bytes())), + 3 => { + out.push((p, p, rng.bytes())); + out.push((p, p, rng.bytes())); + out.push((p, q.min(p + rng.below(4)), rng.bytes())); + } + 4 => out.push((p + (q - p) / 2, q, rng.bytes())), + _ => out.push((q, q, rng.bytes())), + } + } + for i in (1..out.len()).rev() { + out.swap(i, rng.below(i + 1)); + } + out + } + + fn patch(xref: &Xref, edits: &[Edit], objects: bool) -> Patch { + let mut patch = Patch::new(xref); + for (start, end, with) in edits { + patch.replace(*start, *end, with.clone()); + } + if objects { + patch.add_object(b"<< /Added 1 >>".to_vec()); + patch.trailer_entry(b" /Info 2 0 R"); + } + patch + } + + /// Where `off` lands, by walking every edit: how [`Patch::apply`] found it before [`Moves`]. + fn scan(edits: &[Edit], off: usize) -> usize { + edits.iter().filter(|e| e.1 <= off).fold(off as isize, |o, e| o + e.2.len() as isize - (e.1 - e.0) as isize) as usize + } + + /// [`Patch::apply`] as it was written before [`Moves`], walking every edit for every object. + fn apply_by_scan(mut patch: Patch, pdf: &[u8], xref: &Xref) -> Result, PdfError> { + let bad = |why: &str| PdfError::Write(format!("can't edit the written PDF: {why}")); + patch.edits.sort_by_key(|e| (e.0, e.1)); + if patch.edits.windows(2).any(|w| w[0].1 > w[1].0) || patch.edits.iter().any(|e| e.0 > e.1 || e.1 > xref.at) { + return Err(bad("edits overlap")); + } + let edits = &patch.edits; + let moved = |off: usize| -> usize { scan(edits, off) }; + let added: usize = patch.edits.iter().map(|e| e.2.len()).sum::() + patch.objects.iter().map(|o| o.len() + 32).sum::(); + let mut out = Vec::with_capacity(pdf.len() + added + 64); + let mut at = 0; + for (start, end, new) in edits.iter() { + out.extend_from_slice(pdf.get(at..*start).ok_or_else(|| bad("bad edit"))?); + out.extend_from_slice(new); + at = *end; + } + out.extend_from_slice(pdf.get(at..xref.at).ok_or_else(|| bad("bad edit"))?); + let mut offsets = Vec::with_capacity(patch.objects.len()); + for (i, body) in patch.objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", patch.size + i).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let table = out.len(); + let size = patch.size + patch.objects.len(); + out.extend_from_slice(format!("xref\n0 {size}\n").as_bytes()); + let old = pdf.get(xref.entries..xref.entries + 20 * xref.count).ok_or_else(|| bad("bad cross-reference table"))?; + for e in old.chunks(20) { + match number(e, 0) { + Some((off, _)) if e.get(17) == Some(&b'n') => { + out.extend_from_slice(format!("{:010}", moved(off)).as_bytes()); + out.extend_from_slice(e.get(10..).unwrap_or_default()); + } + _ => out.extend_from_slice(e), + } + } + let eol = old.get(18..20).unwrap_or(b"\r\n"); + for off in offsets { + out.extend_from_slice(format!("{off:010} 00000 n").as_bytes()); + out.extend_from_slice(eol); + } + let (ts, te) = xref.trailer; + let dict = pdf.get(ts..te.saturating_sub(2)).ok_or_else(|| bad("bad trailer"))?; + let size_at = find(dict, b"/Size", 0).ok_or_else(|| bad("the trailer has no size"))? + 5; + let (_, size_end) = number(dict, size_at).ok_or_else(|| bad("the trailer has no size"))?; + let (Some(head), Some(tail)) = (dict.get(..size_at), dict.get(size_end..)) else { return Err(bad("bad trailer")) }; + out.extend_from_slice(b"trailer\n"); + out.extend_from_slice(head); + out.extend_from_slice(format!(" {size}").as_bytes()); + out.extend_from_slice(tail); + out.extend_from_slice(&patch.trailer); + out.extend_from_slice(format!(">>\nstartxref\n{table}\n%%EOF").as_bytes()); + Ok(out) + } + + #[test] + fn every_offset_moves_by_the_edits_that_end_at_or_before_it() { + let mut rng = Rng(7661); + for round in 0..100 { + let pdf = written(1 + rng.below(30), |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let mut edits = edits(&pdf, &xref, &mut rng, [0, 1, 3, 20, 80][round % 5]); + edits.sort_by_key(|e| (e.0, e.1)); + let moves = Moves::new(&edits).unwrap(); + for off in 0..=pdf.len() { + assert_eq!(moves.at(off), Some(scan(&edits, off)), "round {round}, offset {off}, edits {edits:?}"); + } + } + } + + #[test] + fn apply_writes_the_bytes_a_walk_of_every_edit_wrote() { + let mut rng = Rng(1378); + for round in 0..300 { + let pdf = written(1 + rng.below(40), |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let edits = edits(&pdf, &xref, &mut rng, [0, 1, 3, 20, 80][round % 5]); + let objects = round % 3 == 0; + let fast = patch(&xref, &edits, objects).apply(&pdf, &xref).unwrap(); + let walked = apply_by_scan(patch(&xref, &edits, objects), &pdf, &xref).unwrap(); + assert_eq!(String::from_utf8_lossy(&fast), String::from_utf8_lossy(&walked), "round {round}"); + } + } + + #[test] + fn every_entry_points_at_its_object_after_the_edits() { + let pdf = written(30, |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let mut patch = Patch::new(&xref); + for (n, off) in xref.objects(&pdf) { + let (at, end) = xref.dict(&pdf, n).unwrap(); + match n % 4 { + 0 => patch.replace(at, at, b" /Grown [1 2 3]".to_vec()), + 1 => patch.replace(at, end, b">>\n".to_vec()), + // An insert at an object's start goes before the object. + 2 => patch.replace(off, off, b"% before\n".to_vec()), + _ => {} + } + } + let added = patch.add_object(b"<< /Added 1 >>".to_vec()); + let out = patch.apply(&pdf, &xref).unwrap(); + let after = Xref::read(&out).unwrap(); + assert_eq!((after.count(), added), (32, 31)); + for n in 1..32u32 { + let Some(off) = after.offset(&out, n) else { + assert!(n % 7 == 3, "object {n} is in use"); + let e = xref.entries + 20 * n as usize; + assert_eq!(out[after.entries + 20 * n as usize..][..20], pdf[e..e + 20], "free entry {n}"); + continue; + }; + assert!(out[off..].starts_with(format!("{n} 0 obj\n").as_bytes()), "object {n} at {off}"); + } + } + + #[test] + fn an_object_moved_past_ten_digits_is_refused() { + let mut pdf = written(2, |_| false); + let entry = Xref::read(&pdf).unwrap().entries + 40; + // Object 2's entry gives the last offset ten digits hold. + pdf[entry..entry + 10].copy_from_slice(b"9999999999"); + let xref = Xref::read(&pdf).unwrap(); + let out = Patch::new(&xref).apply(&pdf, &xref).unwrap(); + assert!(find(&out, b"9999999999 00000 n\r\n", 0).is_some()); + let mut patch = Patch::new(&xref); + patch.replace(9, 9, b"%\n".to_vec()); + let refused = patch.apply(&pdf, &xref); + assert!(matches!(&refused, Err(PdfError::Write(why)) if why.contains("cross-reference table holds")), "{refused:?}"); + } + + /// CPU time this thread has used, where the system reports it (`/proc` on Linux). + fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) + } + + /// How long `f` takes, in thread CPU time where the system reports it, else wall time. + fn time(f: impl FnOnce() -> T) -> (Duration, T) { + let (cpu, wall) = (thread_cpu(), Instant::now()); + let out = f(); + (thread_cpu().zip(cpu).map_or_else(|| wall.elapsed(), |(b, a)| b.saturating_sub(a)), out) + } + + fn median(mut runs: Vec) -> Duration { + runs.sort_unstable(); + runs[runs.len() / 2] + } + + /// `cargo test --release -p vectorcraft-pdf --lib patch::tests::bench -- --ignored --nocapture`. + /// The edits are those of forms in overprint: two inside each form's stream (its `/Length` and + /// data) and an insert into its dictionary, for `n` forms among `n + 20` objects. Each run + /// applies the patch `reps` times, so that small files take long enough for the clock. + #[test] + #[ignore = "timing; run explicitly"] + fn bench_apply_with_many_edits() { + println!("clock: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall time" }); + println!("| forms | objects | edits | walk every edit (median of 7) | binary search (median of 7) |"); + println!("| ---: | ---: | ---: | ---: | ---: |"); + for n in [100, 1_000, 5_000, 20_000] { + let pdf = written(n + 20, |_| false); + let xref = Xref::read(&pdf).unwrap(); + let mut edits = vec![]; + for (obj, _) in xref.objects(&pdf).into_iter().take(n) { + let (at, _) = xref.dict(&pdf, obj).unwrap(); + edits.push((at, at + 1, b" /Length 120 ".to_vec())); + edits.push((at + 1, at + 3, b"/Data".to_vec())); + edits.push((at + 3, at + 3, b" /Resources << /ExtGState << /GS0 9 0 R >> >>".to_vec())); + } + let reps = (200_000_000 / (3 * n * n)).clamp(1, 2_000); + let (mut walked, mut searched) = (vec![], vec![]); + for _ in 0..7 { + let (t, old) = time(|| (0..reps).fold(None, |_, _| apply_by_scan(patch(&xref, &edits, false), &pdf, &xref).ok())); + walked.push(t); + let (t, new) = time(|| (0..reps).fold(None, |_, _| patch(&xref, &edits, false).apply(&pdf, &xref).ok())); + searched.push(t); + assert!(old.is_some() && old == new, "{n} forms: the files differ"); + } + let ms = |d: Duration| d.as_secs_f64() * 1000.0 / reps as f64; + println!("| {n} | {} | {} | {:.3} ms | {:.3} ms |", n + 20, edits.len(), ms(median(walked)), ms(median(searched))); + } + } +} diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index 2313d62129..67c71d5dbc 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -4,9 +4,11 @@ //! - PDF/X-1a:2001: every colour is CMYK, grey or a spot ink with a CMYK alternate (colours and //! images are converted to a CMYK destination and written untagged, see [`crate::output`]), no //! transparency (the app flattens it before writing), no layers, PDF 1.3. -//! - PDF/X-3:2002: colours are ICC-based (always tagged), no transparency, no layers, PDF 1.3. -//! - PDF/X-4:2010: transparency and layers are kept, colours are tagged, PDF 1.6 at most, and the -//! XMP metadata names the standard too and carries `xmp:MetadataDate`. +//! - PDF/X-3:2002: colors are ICC-based (always tagged), except CMYK colors in the CMYK output +//! intent's profile, which are DeviceCMYK (with `profiles` `none`, all CMYK colors unless they +//! are converted to a CMYK destination of another profile), no transparency, no layers, PDF 1.3. +//! - PDF/X-4:2010: transparency and layers are kept, colors are tagged as in PDF/X-3, PDF 1.6 at +//! most, and the XMP metadata names the standard too and carries `xmp:MetadataDate`. //! - All of them: a `/GTS_PDFX` output intent (blank, the CMYK profile in effect, embedded), a //! TrimBox on every page (the artboard), `/Trapped` True or False, `/GTS_PDFXVersion` in the //! document information, a title and dates, embedded fonts (or text as outlines), no editing diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 74102373e5..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}; @@ -171,36 +171,78 @@ impl<'a> Separator<'a> { /// swatch link). Any ink above zero puts ink down, except on PostScript plates for a color that /// counts as 100% black ([`vectorcraft_doc::overprint::is_black_ink`], as /// [`vectorcraft_doc::overprint::OverprintBlack::default`] judges it) and is not linked to a - /// spot swatch, to Registration or to a swatch the document lacks: up to the half a percent of - /// another ink such a black may carry counts as none. + /// spot swatch or to Registration: up to the half a percent of another ink such a black may + /// 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_some_and(|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); @@ -211,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.rs b/crates/pdf/src/tests.rs index 91c037ad84..e2abe87637 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1449,6 +1449,41 @@ fn empty_and_populated_file_info_preserve_key_presence() { assert!(s.contains("/ViewerPreferences<>"), "viewers should show the document title (#3646)"); } +/// The text of the `/Lang` entry of the catalog of `pdf` (a literal string), if any. +fn catalog_lang(pdf: &[u8]) -> Option { + let xref = crate::patch::Xref::read(pdf).expect("a cross-reference table"); + let root = xref.trailer_ref(pdf, b"/Root").expect("a catalog"); + let (start, end) = xref.dict(pdf, root).expect("the catalog's dictionary"); + let catalog = String::from_utf8_lossy(&pdf[start..end]).into_owned(); + let at = catalog.find("/Lang")? + "/Lang".len(); + let rest = catalog[at..].trim_start().strip_prefix('(').expect("a literal string"); + Some(rest[..rest.find(')').expect("a closed string")].to_string()) +} + +/// The catalog gives the document language chosen in Document Setup as its BCP 47 tag, in +/// exported and printed PDFs, and the XMP packet says it too (#3644). +#[test] +fn the_catalog_gives_the_document_language() { + let mut d = doc(100.0, 100.0); + for (language, tag) in [(None, "en-US"), (Some("French"), "fr"), (Some("German: Swiss"), "de-CH")] { + if let Some(language) = language { + d.setup.language = language.into(); + } + for opts in [PdfOptions::uncompressed(), PdfOptions::default()] { + let bytes = export(&d, &opts).unwrap(); + assert_eq!(catalog_lang(&bytes).as_deref(), Some(tag), "{language:?}"); + } + // Print to PDF writes its file with the same writer. + let printed = print(&d, &PrintOptions { created: Some(1_700_000_000), ..Default::default() }).unwrap(); + assert_eq!(catalog_lang(&printed.bytes).as_deref(), Some(tag), "{language:?}: printed"); + let s = uncompressed(&d); + assert!(s.contains(&format!("{tag}")), "{language:?}: {s}"); + } + // A language without a tag (from a file) writes none rather than a guess. + d.setup.language = "Klingon".into(); + assert_eq!(catalog_lang(&export(&d, &PdfOptions::uncompressed()).unwrap()), None); +} + /// A function or colour space built on itself is refused before the interpreter builds it (by /// recursion, with no cap: a stack overflow), and those of real files are read. #[test] diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 4d22a10ee6..ec157a8182 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -36,21 +36,33 @@ fn stream(dict: &str, data: &[u8]) -> Vec { /// A 300 × 100 pt page with a CMYK rectangle and image XObjects `images` (dictionary entries /// after the type, stream data), 50 pt wide each: objects 5…, then the `extra` objects. fn pdf_with_images(images: &[(String, Vec)], extra: &[Vec]) -> Vec { + pdf_with(images, extra, "", "") +} + +/// [`pdf_with_images`] with `catalog` added to the catalog's entries and `resources` to the +/// page's resources. +fn pdf_with(images: &[(String, Vec)], extra: &[Vec], catalog: &str, resources: &str) -> Vec { let xobjects: String = (0..images.len()).map(|i| format!("/Im{i} {} 0 R ", 5 + i)).collect(); let mut content = String::from("0 1 0.6 0.2 k 0 80 300 20 re f\n"); for i in 0..images.len() { content.push_str(&format!("q 50 0 0 50 {} 10 cm /Im{i} Do Q\n", 10 + 60 * i)); } let mut objs = vec![ - b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + format!("<< /Type /Catalog /Pages 2 0 R {catalog}>>").into_bytes(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << {xobjects}>> >> /Contents 4 0 R >>").into_bytes(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << {xobjects}>> {resources}>> /Contents 4 0 R >>") + .into_bytes(), stream("", content.as_bytes()), ]; for (dict, data) in images { objs.push(stream(&format!("/Type /XObject /Subtype /Image {dict}"), data)); } objs.extend_from_slice(extra); + pdf_of(&objs) +} + +/// A PDF file of `objs`, numbered from 1, whose catalog is object 1. +fn pdf_of(objs: &[Vec]) -> Vec { let mut out = b"%PDF-1.4\n".to_vec(); let mut at = vec![]; for (i, o) in objs.iter().enumerate() { @@ -164,8 +176,9 @@ fn a_cmyk_jpeg_passes_through_open_and_every_pdf_export() { (json!({}), "DeviceCMYK", None), (json!({"output": {"conversion": "preserveNumbers"}}), "DeviceCMYK", None), (json!({"standard": "pdfX1a"}), "DeviceCMYK", None), - (json!({"standard": "pdfX3"}), "ICCBased", Some(4)), - (json!({"standard": "pdfX4"}), "ICCBased", Some(4)), + // CMYK in the output intent's profile (the CMYK profile in effect) is DeviceCMYK. + (json!({"standard": "pdfX3"}), "DeviceCMYK", None), + (json!({"standard": "pdfX4"}), "DeviceCMYK", None), (json!({"output": {"profiles": "all"}}), "ICCBased", Some(4)), ] { let out = export_with_report(&r.document, &opts(settings.clone())).unwrap(); @@ -178,12 +191,14 @@ fn a_cmyk_jpeg_passes_through_open_and_every_pdf_export() { assert!(out.warnings.iter().all(|w| !w.contains("image")), "{settings}: {:?}", out.warnings); // And open again: the same JPEG, carrying the profile it was written in when it was // ICC-based. + // ICC-based, or DeviceCMYK in a PDF/X file, whose output intent's profile it then carries. let back = import(&out.bytes).unwrap(); let blob = blobs(&back)[0]; - if icc_n.is_some() { + let intent = settings.get("standard").is_some().then(|| cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + if let Some(icc) = w[0].icc.clone().or(intent) { assert_eq!(blob.mime, "image/jpeg", "{settings}"); assert_eq!(blob.cmyk(), b[0].cmyk(), "{settings}: the same samples"); - assert_eq!(blob.cmyk_icc_profile(), w[0].icc, "{settings}: the profile it was written in"); + assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(&*icc), "{settings}: the profile it was written in"); } else { assert_eq!(blob.bytes.as_slice(), jpg.as_slice(), "{settings}"); } @@ -645,6 +660,117 @@ fn a_cmyk_image_that_keeps_its_numbers_carries_its_cmyk_profile() { assert!(!String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); } +/// When CMYK colors are DeviceCMYK in the output intent's profile, a CMYK image that carries that +/// profile is DeviceCMYK too, and with `none` so is one that carries another profile; elsewhere +/// it keeps its own (#1954). +#[test] +fn a_cmyk_image_in_the_output_intents_profile_is_device_cmyk() { + let ink = [0u8, 102, 255, 0]; + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + let other = cmyk_profile(|_| {}); + let export = |icc: &[u8], s: serde_json::Value| { + let tiff = cmyk_tiff_with(ink, 4, 4, icc); + let inks = tiff.cmyk().unwrap().data; + let d = image_doc(tiff, 4, 4); + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert_eq!(w.len(), 1, "{s}: {w:?}"); + assert_eq!(blobs(&import(&out.bytes).unwrap())[0].cmyk().unwrap().data, inks, "{s}: the inks as they were"); + w.into_iter().next().unwrap() + }; + for s in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX3"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] { + let w = export(&working, s.clone()); + assert_eq!((w.space.as_str(), w.icc_n), ("DeviceCMYK", None), "{s}: the output intent's profile"); + } + let w = export(&other, json!({"standard": "pdfX4"})); + assert!((w.space.as_str(), w.icc.as_deref()) == ("ICCBased", Some(other.as_slice())), "another profile is kept: {w:?}"); + let w = export(&other, json!({"standard": "pdfX4", "output": {"profiles": "none"}})); + assert_eq!((w.space.as_str(), w.icc_n), ("DeviceCMYK", None), "with none: {w:?}"); + // Without an output intent, the image keeps the profile it carries. + let w = export(&working, json!({"output": {"profiles": "all"}})); + assert!(w.space == "ICCBased" && w.icc.as_deref() == Some(&*working), "{w:?}"); +} + +/// A DeviceCMYK image in a file with a PDF/X output intent of CMYK opens tagged with the intent's +/// profile, so a CMYK image written as DeviceCMYK in that profile opens with it again. Without an +/// output intent it opens untagged. +#[test] +fn a_device_cmyk_image_opens_with_the_pdfx_output_intents_profile() { + let ink = [0u8, 102, 255, 0]; + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + for (s, tagged) in [(json!({"standard": "pdfX4"}), true), (json!({"standard": "pdfX3"}), true), (json!({}), false)] { + let d = image_doc(cmyk_tiff_with(ink, 4, 4, &working), 4, 4); + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert!(w.len() == 1 && w[0].space == "DeviceCMYK", "{s}: {w:?}"); + let opened = import(&out.bytes).unwrap(); + let icc = blobs(&opened)[0].cmyk_icc_profile(); + assert_eq!(icc.as_deref(), tagged.then_some(&*working), "{s}"); + } +} + +/// In a file whose catalog has a CMYK `/GTS_PDFX` output intent, a DeviceCMYK image opens tagged +/// with the intent's profile; another kind of output intent tags nothing, and neither does the +/// intent on a page whose resources replace DeviceCMYK with a `/DefaultCMYK`. +#[test] +fn a_device_cmyk_image_takes_the_output_intent_unless_a_default_cmyk_replaces_it() { + let (intent, other) = (cmyk_profile(|_| {}), cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + assert_ne!(intent, other); + let image = [(cmyk_dict(2, 2, ""), flat([0, 102, 255, 0], 4))]; + let profiles = [stream("/N 4", &intent), stream("/N 4", &other)]; + let pdfx = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Test) /DestOutputProfile 6 0 R >>] "; + let pdfa = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFA1 /OutputConditionIdentifier (Test) /DestOutputProfile 6 0 R >>] "; + let default_cmyk = "/ColorSpace << /DefaultCMYK [/ICCBased 7 0 R] >> "; + for (catalog, resources, expected) in [(pdfx, "", Some(&intent)), ("", "", None), (pdfa, "", None), (pdfx, default_cmyk, None)] { + let d = import(&pdf_with(&image, &profiles, catalog, resources)).unwrap(); + let b = blobs(&d); + assert_eq!(b.len(), 1, "{catalog} {resources}"); + assert_eq!(b[0].cmyk().unwrap().data, flat([0, 102, 255, 0], 4), "{catalog} {resources}: the inks as they were"); + assert_eq!(b[0].cmyk_icc_profile().as_deref(), expected.map(Vec::as_slice), "{catalog} {resources}"); + } +} + +/// A `/DefaultCMYK` stops the output intent from tagging a DeviceCMYK image only where it is in +/// scope: on the page's own image when only a form on the page has one, the image keeps the +/// intent's profile; drawn inside that form, it opens untagged; and the same image drawn on a page +/// with a `/DefaultCMYK` and then on a page without one opens untagged on the first and tagged on +/// the second. +#[test] +fn the_output_intent_tags_a_device_cmyk_image_only_where_no_default_cmyk_is_in_scope() { + let (intent, other) = (cmyk_profile(|_| {}), cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + let default = "/ColorSpace << /DefaultCMYK [/ICCBased 8 0 R] >>"; + // Objects: 1 catalog, 2 pages, 3 and 4 the pages, 5 their content, 6 the image, 7 and 8 the + // profiles, 9 a form with a `/DefaultCMYK`. + let file = |pages: &[&str], content: &str, form: &str| { + let kids: String = (0..pages.len()).map(|i| format!("{} 0 R ", 3 + i)).collect(); + let page = |res: &str| format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << {res} >> /Contents 5 0 R >>").into_bytes(); + let form_dict = format!("/Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /XObject << /Im0 6 0 R >> {default} >>"); + pdf_of(&[ + b"<< /Type /Catalog /Pages 2 0 R /OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Test) /DestOutputProfile 7 0 R >>] >>".to_vec(), + format!("<< /Type /Pages /Kids [{kids}] /Count {} >>", pages.len()).into_bytes(), + page(pages[0]), + page(pages.get(1).copied().unwrap_or("")), + stream("", content.as_bytes()), + stream(&format!("/Type /XObject /Subtype /Image {}", cmyk_dict(2, 2, "")), &flat([0, 102, 255, 0], 4)), + stream("/N 4", &intent), + stream("/N 4", &other), + stream(&form_dict, form.as_bytes()), + ]) + }; + let image = "q 50 0 0 50 10 10 cm /Im0 Do Q "; + let form = "q 50 0 0 50 80 10 cm /Fm0 Do Q "; + let cases = [ + (file(&["/XObject << /Im0 6 0 R /Fm0 9 0 R >>"], &format!("{image}{form}"), "0 0 0 1 k 0 0 1 1 re f"), vec![Some(&intent)]), + (file(&["/XObject << /Fm0 9 0 R >>"], form, "/Im0 Do"), vec![None]), + (file(&[&format!("/XObject << /Im0 6 0 R >> {default}"), "/XObject << /Im0 6 0 R >>"], image, ""), vec![None, Some(&intent)]), + ]; + for (i, (bytes, expected)) in cases.into_iter().enumerate() { + let d = import(&bytes).unwrap(); + let profiles: Vec>> = all_images(&d).iter().map(|b| b.cmyk_icc_profile().map(|p| p.to_vec())).collect(); + assert_eq!(profiles, expected.into_iter().map(|p| p.cloned()).collect::>(), "case {i}"); + } +} + /// With Don't Include Profiles set, a CMYK JPEG kept as it is is DeviceCMYK without its own /// `ICC_PROFILE` segments, its compressed inks unchanged; one resampled and compressed again is /// written without a profile too. Left unset, the JPEG data stays as it is. @@ -672,6 +798,16 @@ fn a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out() { let s = json!({"output": {"profiles": "none"}, "compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); let (w, _) = export(s.clone()); assert!(w.icc.is_none() && !segment(&w.data), "{s}: {w:?}"); + // A PDF/X file whose CMYK colors are DeviceCMYK takes the profile out of a JPEG it untags. + let s = json!({"standard": "pdfX4", "output": {"profiles": "none"}}); + let (w, _) = export(s.clone()); + assert!(w.space == "DeviceCMYK" && w.data == vectorcraft_doc::cmyk::jpeg_without_icc(&jpg).unwrap(), "{s}: {w:?}"); + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + let own = cmyk_jpeg_with(&flat(ink, 64 * 64), 64, 64, &working); + let d = image_doc(ImageBlob::new("image/jpeg", own.clone()), 64, 64); + let out = export_with_report(&d, &opts(json!({"standard": "pdfX4"}))).unwrap(); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert!(w.len() == 1 && w[0].space == "DeviceCMYK" && w[0].data == vectorcraft_doc::cmyk::jpeg_without_icc(&own).unwrap(), "{w:?}"); } /// A CMYK JPEG kept as it is whose header declares far more pixels than the app reads is left out diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index c4f2900709..b58c953c2f 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -237,3 +237,104 @@ fn a_file_name_written_as_utf16_is_found() { assert_eq!(e.data, b"hello", "/{key}"); } } + +#[test] +fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() { + // No `EF` dictionary, an `EF` without `F` or `UF`, and an `F` naming no object. + for ef in ["", "/EF << >>", "/EF << /F 9 0 R >>"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".to_string(), + "<< /Names [(a) 4 0 R] >>".to_string(), + format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{ef:?}"); + assert!(opened.has_editing_file(), "{ef:?}"); + } + // A name tree key naming it, with a file specification that names no object or isn't one. + for spec in ["9 0 R", "(not a file specification)"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Names [(a) 9 0 R ({EDITING_FILE}) {spec}] >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{spec}"); + assert!(opened.has_editing_file(), "{spec}"); + } + // The key written as an indirect string. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + "<< /Names [5 0 R 9 0 R] >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + format!("({EDITING_FILE})"), + ]; + assert!(open_pdf(&raw_pdf(&objects), None).unwrap().has_editing_file()); + // A PDF without the editing file, and one with it. + assert!(!open_pdf(&export(&doc(), &PdfOptions::default()).unwrap(), None).unwrap().has_editing_file()); + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && opened.has_editing_file()); +} + +#[test] +fn an_editing_file_deep_in_the_name_tree_is_found() { + // Objects 4..=203 are a chain of 200 name tree nodes, each listing the next one; the editing + // file sits in the leaf (object 204), with its data or naming data that can't be resolved. + for ef in ["/EF << /F 206 0 R >>", "/EF << /F 999 0 R >>"] { + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [207 0 R] /Count 1 >>".to_string(), + "<< /Kids [4 0 R] >>".to_string(), + ]; + for node in 4..=203 { + objects.push(format!("<< /Kids [{} 0 R] >>", node + 1)); + } + objects.push("<< /Names [(a) 205 0 R] >>".to_string()); + objects.push(format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>")); + objects.push("<< /Length 5 >>\nstream\nhello\nendstream".to_string()); + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string()); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert!(opened.has_editing_file(), "{ef}"); + let data = opened.editing().map(|e| e.data); + assert_eq!(data.as_deref(), ef.contains("206").then_some(&b"hello"[..]), "{ef}"); + } + // A name tree with more nodes than are searched may list it. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [{}] >>", "<< /Names [] >> ".repeat(70_000)), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // One that lists a readable editing file before the nodes left unsearched and another after + // them: the first is read, and the search reads as cut short. + let leaf = |stream: u32| format!("<< /Names [({EDITING_FILE}) << /Type /Filespec /UF ({EDITING_FILE}) /EF << /F {stream} 0 R >> >>] >>"); + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [8 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [4 0 R {}5 0 R] >>", "<< /Names [] >> ".repeat(70_000)), + leaf(6), + leaf(7), + "<< /Length 5 >>\nstream\nfirst\nendstream".to_string(), + "<< /Length 6 >>\nstream\nsecond\nendstream".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // The same, with the nodes past the limit in a subtree after the one holding the first. + let mut objects = objects; + objects[2] = format!("<< /Kids [4 0 R << /Kids [{}5 0 R] >>] >>", "<< /Names [] >> ".repeat(70_000)); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // A tree searched to its end. + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && !opened.editing_search_cut()); +} diff --git a/crates/pdf/src/tests/fx.rs b/crates/pdf/src/tests/fx.rs index cd73c01bb9..709031a6a2 100644 --- a/crates/pdf/src/tests/fx.rs +++ b/crates/pdf/src/tests/fx.rs @@ -1,9 +1,11 @@ -//! Raster effects in PDF export: not written yet, so a fill's, a stroke's or the object's own -//! raster effect is reported. +//! Effects in PDF export: raster effects are not written yet, so a fill's, a stroke's or the +//! object's own raster effect is reported; geometry effects are baked into what the file draws. + +use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, Effect, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; use crate::*; @@ -27,3 +29,50 @@ fn raster_effects_warn_on_fills_strokes_and_objects() { assert!(warnings(item).iter().any(|w| w.starts_with("raster effects")), "{item:?}"); } } + +/// What `n` paints, in paint order, with consecutive repeats dropped: 'b' for a blue fill, 'r' for a +/// red fill and 'g' for a green stroke, each with whether a clip group clips it. Clipping paths +/// themselves are left out. +fn painted_order(n: &Node, clipped: bool, out: &mut Vec<(char, bool)>) { + let solid = |p: &Paint, r: f32, g: f32, b: f32| matches!(p, Paint::Solid { color, .. } if *color == Color::rgb(r, g, b)); + for i in &n.appearance.items { + let mark = match i { + AppearanceItem::Fill(f) if solid(&f.paint, 0.0, 0.0, 1.0) => 'b', + AppearanceItem::Fill(f) if solid(&f.paint, 1.0, 0.0, 0.0) => 'r', + AppearanceItem::Stroke(s) if s.width > 0.0 && solid(&s.paint, 0.0, 1.0, 0.0) => 'g', + _ => continue, + }; + if out.last() != Some(&(mark, clipped)) { + out.push((mark, clipped)); + } + } + let clips = matches!(n.kind, NodeKind::Group { clip: true, .. }); + for c in n.children().into_iter().flatten().skip(usize::from(clips)) { + painted_order(c, clipped || clips, out); + } +} + +#[test] +fn painted_clipping_type_exports_with_group_effect() { + // Type filled blue and stroked green clips a red square in a group with an Offset Path effect: + // the PDF paints the type's fill inside the clip behind the square, and its stroke over the + // clipped art, outside the clip. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let style = CharStyle { size: 40.0, fill: blue, stroke: green, stroke_width: 2.0, ..Default::default() }; + let mut d = Document::new(200.0, 200.0); + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), red); + let clip = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(text), Arc::new(square)], clip: true }); + let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + outer.appearance.effects.push(Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 1}), visible: true }); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, outer).unwrap(); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); + let mut order = vec![]; + for l in &back.layers { + painted_order(l, false, &mut order); + } + assert_eq!(order, [('b', true), ('r', true), ('g', false)]); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 251cc925bf..188ca0e80d 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -507,6 +507,56 @@ fn a_form_drawn_many_times_reads_its_font_resources_once() { assert_eq!(walk.fonts.len(), 1); } +/// A Type 3 font that every page lists in a font dictionary of its own, and a form lists in its +/// resources, has its glyph procedures read once for the document. Each page still maps the font's +/// glyphs, and the font whose glyphs set their own color (`d0`) is told from the one whose glyphs +/// don't (`d1`). +#[test] +fn a_type3_font_on_every_page_has_its_glyph_procedures_read_once() { + const PAGES: usize = 6; + let n = first_extra(PAGES); + let (shape, color, shape_a, shape_b, color_a, form) = (n, n + 1, n + 2, n + 3, n + 4, n + 5); + let font = |name: &str, procs: &str| { + format!( + "<< /Type /Font /Subtype /Type3 /Name /{name} /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << {procs} >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [1000 1000] /Resources << >> >>" + ) + }; + let objects = [ + font("Vcshape", &format!("/a {shape_a} 0 R /b {shape_b} 0 R")), + font("Vccolor", &format!("/a {color_a} 0 R /b {color_a} 0 R")), + stream("", "1000 0 0 0 1000 1000 d1 0 0 1000 1000 re f"), + stream("", "1000 0 0 0 1000 1000 d1 0 0 500 500 re f"), + stream("", "1000 0 d0 1 0 0 rg 0 0 1000 1000 re f"), + stream( + &format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /Font << /C {color} 0 R /S {shape} 0 R >> >>"), + "BT /S 12 Tf (ab) Tj /C 12 Tf (ab) Tj ET", + ), + ]; + let pages: Vec = (0..PAGES) + .map(|_| PdfPage { + resources: format!("/Font << /S {shape} 0 R /C {color} 0 R >> /XObject << /X0 {form} 0 R >>"), + ..PdfPage::new(100.0, 100.0, "BT /S 24 Tf 10 30 Td (ab) Tj /C 24 Tf (ab) Tj ET /X0 Do") + }) + .collect(); + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + let pdf = craft_pdf::syntax::Pdf::new(pdf_with(&pages, &extra, None)).unwrap(); + let mut fonts = crate::import_scan::FontNames::new(); + let mut ocgs = crate::import_scan::Ocgs::read(&pdf); + crate::import_scan::TEST_CHARPROC_DECODES.with(|d| d.set(0)); + for page in pdf.pages().iter() { + let scan = crate::import_scan::scan_page(page, &mut ocgs, false, &mut fonts, pdf.decode_limits().max_decoded_stream()).unwrap(); + let mapped: std::collections::HashSet<(u128, bool)> = scan.type3_cache_map.values().copied().collect(); + let noted: std::collections::HashSet<(u128, bool)> = fonts.keys().map(|k| (*k, false)).collect(); + assert_eq!(scan.type3_cache_map.len(), 2 * 257); + assert_eq!(mapped, noted); + let mut colors: Vec<(String, bool)> = fonts.values().map(|f| (f.name.clone(), f.is_colour)).collect(); + colors.sort(); + assert_eq!(colors, [("Vccolor".to_string(), true), ("Vcshape".to_string(), false)]); + } + // The `d1` font's two procedures and the `d0` font's one. + assert_eq!(crate::import_scan::TEST_CHARPROC_DECODES.with(std::cell::Cell::get), 3); +} + /// A value of the page's font dictionary that the reader can't parse (a name with a broken `#` /// escape, a number with a stray `-`) is left out when the page's fonts are noted, and the fonts /// after it are noted. diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index 71461ae1f8..d9c2fedc1d 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -591,39 +591,96 @@ fn standard_pdf(d: &Document, settings: Value) -> ExportReport { export_with_report(d, &PdfOptions { settings, created: Some(1_700_000_000), ..Default::default() }).unwrap() } +/// The output intent's profile, decoded, of `bytes`. +fn intent_profile(bytes: &[u8]) -> Vec { + let mut out = vec![]; + output_intent(bytes, None, |oi| out = oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().into_owned()); + out +} + +/// CMYK colors in the profile of a CMYK output intent are DeviceCMYK, which the output intent +/// describes: no ICC-based CMYK space carries the same profile, and it is embedded once (#1954). #[test] -fn a_profile_that_tags_colours_and_is_the_output_intent_is_embedded_once() { - let d = doc(ColorMode::Cmyk, &[Color::cmyk(0.1, 0.2, 0.3, 0.4)]); +fn cmyk_colors_in_the_output_intents_profile_are_device_cmyk() { + let ink = [0.1, 0.2, 0.3, 0.4]; + let d = doc(ColorMode::Cmyk, &[Color::cmyk(ink[0], ink[1], ink[2], ink[3])]); let working = cms::active_settings().cmyk; let icc = cms::icc_bytes(&working).unwrap(); for set in [ json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"outputIntent": working}}), - // PDF/X-3 and PDF/X-4 always tag their colours: `profiles` doesn't apply. json!({"standard": "pdfX4", "output": {"profiles": "none", "outputIntent": working}}), json!({"standard": "pdfX3"}), - json!({"output": {"profiles": "all", "outputIntent": working}}), ] { let r = standard_pdf(&d, set.clone()); - let streams = icc_streams(&r.bytes); - assert_eq!(streams.len(), 1, "{set}: ICC profile streams"); - assert!(streams[0] == *icc, "{set}: the working CMYK profile"); - assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: tagged colours"); - output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*icc)); + assert!(r.warnings.is_empty(), "{set}: {:?}", r.warnings); + assert!(icc_streams(&r.bytes) == [icc.to_vec()], "{set}: the working CMYK profile, once"); + assert!(icc_profiles(&r.bytes).is_empty(), "{set}: no ICC-based color space"); + let c = colours(&r.bytes); + assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: DeviceCMYK, the numbers kept: {c:?}"); + assert!(intent_profile(&r.bytes) == *icc, "{set}"); } - // Another output intent profile is its own stream. + // Another output intent's profile: CMYK colors keep their own, and both are embedded. + let other = cms::icc_bytes(DEVICE_CMYK).unwrap(); let r = standard_pdf(&d, json!({"standard": "pdfX4", "output": {"outputIntent": DEVICE_CMYK}})); assert_eq!(icc_streams(&r.bytes).len(), 2); - output_intent(&r.bytes, None, |oi| { - assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*cms::icc_bytes(DEVICE_CMYK).unwrap()) - }); + assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())]); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{:?}", colours(&r.bytes)); + assert!(intent_profile(&r.bytes) == *other); + // With `none`, every CMYK color is DeviceCMYK, in the output intent's profile. + for standard in ["pdfX3", "pdfX4"] { + let set = json!({"standard": standard, "output": {"profiles": "none", "outputIntent": DEVICE_CMYK}}); + let r = standard_pdf(&d, set.clone()); + assert!(icc_streams(&r.bytes) == [other.to_vec()], "{set}"); + let c = colours(&r.bytes); + assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: {c:?}"); + } + // With `none`, colors converted to a CMYK destination of another profile keep its tag: they + // are in the destination's profile, not the output intent's. + let set = json!({"standard": "pdfX4", "output": {"profiles": "none", "conversion": "destination", "destination": DEVICE_CMYK, "outputIntent": working}}); + let r = standard_pdf(&d, set.clone()); + assert!(icc_profiles(&r.bytes) == [(4, other.to_vec())], "{set}"); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes)); + assert!(intent_profile(&r.bytes) == *icc, "{set}"); + // Without a standard, `all` tags CMYK colors, with an output intent of their profile or none. + for set in [json!({"output": {"profiles": "all"}}), json!({"output": {"profiles": "all", "outputIntent": working}})] { + let r = standard_pdf(&d, set.clone()); + assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())], "{set}"); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes)); + } +} + +/// Next to DeviceCMYK colors, RGB colors stay ICC-based (a CMYK output intent leaves no room for +/// DeviceRGB), and transparency groups of a CMYK document blend in DeviceCMYK. +#[test] +fn rgb_stays_tagged_and_groups_blend_in_device_cmyk_beside_device_cmyk_colors() { + let d = doc(ColorMode::Rgb, &[Color::rgb(0.2, 0.4, 0.6), Color::cmyk(0.1, 0.2, 0.3, 0.4)]); + for set in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] { + let r = standard_pdf(&d, set.clone()); + let ops: Vec = colours(&r.bytes).into_iter().map(|c| c.0).collect(); + assert_eq!(ops, ["scn", "k"], "{set}"); + let n: Vec = icc_profiles(&r.bytes).iter().map(|p| p.0).collect(); + assert_eq!(n, [3], "{set}: sRGB only"); + } + let mut d = doc(ColorMode::Cmyk, &[Color::cmyk(1.0, 0.0, 0.0, 0.0)]); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + n.opacity = 0.5; + let l = d.layers[0].id; + d.insert(Some(l), 1, n).unwrap(); + let r = standard_pdf(&d, json!({"standard": "pdfX4"})); + let text = String::from_utf8_lossy(&r.bytes); + let groups: Vec<&str> = text.split("/Group<<").skip(1).map(|g| g.split(">>").next().unwrap()).collect(); + assert!(!groups.is_empty() && groups.iter().all(|g| g.contains("/CS/DeviceCMYK")), "{groups:?}"); } /// The profiles assigned to a document (Edit › Assign Profile) are its colour spaces whatever the /// working spaces of the session that exports it: a document opened again in a new session, -/// which starts with the default working spaces, keeps its profiles. Its CMYK colours are tagged -/// with its CMYK profile, which is also the PDF/X output intent, and its RGB colours separate -/// through it. +/// which starts with the default working spaces, keeps its profiles. Its CMYK profile is the PDF/X +/// output intent, whose DeviceCMYK colors are in it, and its RGB colours separate through it. #[test] fn colours_are_in_the_profiles_assigned_to_the_document() { let working = cms::active_settings().cmyk; @@ -635,13 +692,13 @@ fn colours_are_in_the_profiles_assigned_to_the_document() { let r = standard_pdf(&d, json!({"standard": "pdfX4"})); assert!(!r.warnings.iter().any(|w| w.contains("profile")), "{:?}", r.warnings); let own = cms::icc_bytes(DEVICE_CMYK).unwrap(); - assert!(icc_streams(&r.bytes) == [own.to_vec()], "tagged with the document's CMYK profile, not the working one"); + assert!(icc_streams(&r.bytes) == [own.to_vec()], "the document's CMYK profile, not the working one"); output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*own)); let c = colours(&r.bytes); - assert!(c[0].0 == "scn" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}"); + assert!(c[0].0 == "k" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}"); let separated = to_cmyk(DEVICE_CMYK).to_cmyk(&grey, intent); assert!(!close(&separated, &cms::active().to_cmyk(&grey, intent)), "the two profiles separate grey differently"); - assert!(c[1].0 == "scn" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}"); + assert!(c[1].0 == "k" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}"); // A profile that isn't available leaves the working space, with a warning. d.color_profiles.cmyk = Some("No Such Press".into()); let r = standard_pdf(&d, json!({"standard": "pdfX4"})); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 49a34ff428..bee9e61bad 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -829,6 +829,80 @@ fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_p assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 4), "the cyan plate, the Black plate"); } +#[test] +fn overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates() { + // 0.4% cyan beside 100% K, linked to a swatch the document lacks: it separates from its own + // values and the option marks it to overprint, so it counts as black like an unlinked color. + let near = Paint::Solid { color: Color::cmyk(0.004, 0.0, 0.0, 1.0), swatch: Some("Missing".into()), tint: 1.0 }; + let square = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), Appearance::basic(near, Paint::None, 0.0)); + let d = over_cyan(vec![square]); + assert!(d.swatch("Missing").is_none()); + let opts = PrintOptions { + settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), + postscript: true, + ..Default::default() + }; + let p = plan(&d, &opts).unwrap(); + let fills = |doc: &Document| { + let mut count = 0; + doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 2), "the cyan plate, the Black plate"); +} + +#[test] +fn overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates() { + // 0.4% cyan beside 100% K, linked to a swatch the document lacks and set to overprint, on a + // fill, a stroke, a character fill and a linear gradient's stops: a PostScript cyan plate draws + // it as nothing, as it does an unlinked black, and a PDF cyan plate draws it. A faint cyan that + // is not black, linked to the same name, stays on both. + let missing = |color: Color| Paint::Solid { color, swatch: Some("Missing".into()), tint: 1.0 }; + let near = Color::cmyk(0.004, 0.0, 0.0, 1.0); + let faint = Color::cmyk(0.004, 0.5, 0.0, 0.0); + let square = |x: f64, fill: Paint, stroke: Paint| { + let mut n = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 2.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + if let Some(s) = n.appearance.stroke_mut() { + s.overprint = true; + } + n + }; + let stop = |offset: f32| GradientStop { swatch: Some("Missing".into()), ..GradientStop::new(offset, near) }; + let linear = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop(0.0), stop(1.0)])); + let style = vectorcraft_doc::CharStyle { fill: missing(near), overprint_fill: true, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let d = over_cyan(vec![ + square(10.0, missing(near), Paint::None), + square(40.0, Paint::None, missing(near)), + square(70.0, Paint::Gradient(Box::new(linear)), Paint::None), + square(100.0, missing(faint), Paint::None), + Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))), + ]); + assert!(d.swatch("Missing").is_none()); + // The fills, strokes and character fills plate `plate` draws. + let drawn = |postscript: bool, plate: usize| { + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let (mut fills, mut strokes, mut chars) = (0, 0, 0); + p.plates[plate].walk(|n| { + fills += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())); + strokes += usize::from(n.appearance.stroke().is_some_and(|s| !s.paint.is_none())); + if let NodeKind::Text(t) = &n.kind { + chars += t.runs.iter().filter(|r| !r.style.fill.is_none()).count(); + } + }); + (fills, strokes, chars) + }; + assert_eq!(drawn(true, 0), (2, 0, 0), "PostScript cyan plate: the cyan and the faint fill"); + assert_eq!(drawn(false, 0), (4, 1, 1), "PDF cyan plate: the cyan, the fill, the gradient, the faint fill, the stroke and the type"); + assert_eq!(drawn(true, 3), (3, 1, 1), "PostScript Black plate: every black, not the faint fill"); +} + #[test] fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { // 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript @@ -925,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/plugins/src/lib.rs b/crates/plugins/src/lib.rs index b304e1721e..019dd0d858 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -53,7 +53,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; -pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms}; +pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 5a2db2ff0d..0cb6197e97 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -35,6 +35,11 @@ pub const HEAVY_FUEL: u64 = 1_000_000_000; /// Wall-clock budget of a heavy filter's run, in milliseconds. pub const HEAVY_WALL_TIME_MS: u64 = 300_000; +/// Instructions a filter's run may use besides [`Limits::fuel_per_byte`] for each byte of input +/// when Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget is Large +/// ([`Plugin::large_limits`]): 5 times the default. +pub const LARGE_FUEL: u64 = 250_000_000; + /// The limit a run reports when its input and parameters together are past half its memory. pub(crate) const SELECTION_TOO_LARGE: &str = "memory budget (the selection is too large to hand over)"; @@ -215,6 +220,12 @@ impl Plugin { pub fn limits(&self) -> &Limits { &self.limits } + /// Its limits with the Large instruction budget: at least [`LARGE_FUEL`] instructions besides + /// those for each byte of input, and every other limit, the time budget included, as it is. A + /// heavy filter keeps its larger budget. + pub fn large_limits(&self) -> Limits { + Limits { fuel_base: self.limits.fuel_base.max(LARGE_FUEL), ..self.limits.clone() } + } /// Module size in bytes. pub fn size(&self) -> usize { self.size diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index abc2cd05eb..26dec0a7d2 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -7,7 +7,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; -use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; +use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; /// The example Desaturate plug-in, built from `crates/plugins/example`. const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm"); @@ -259,6 +259,23 @@ fn a_heavy_filter_finishes_what_a_light_one_cannot() { assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); } +/// The Large instruction budget gives a light filter 5 times the instructions besides those for +/// each byte of input, so it finishes 20 million steps of a loop that its own budget can't, in the +/// same time budget. A heavy filter keeps its larger budget, and every other limit stays. +#[test] +fn the_large_budget_finishes_what_a_light_one_cannot_and_keeps_a_heavy_one() { + let light = Plugin::load(&build(&tpl::spinning(MANIFEST, 20_000_000, INPUT)), Limits::default()).unwrap(); + assert_eq!(light.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into()))); + let large = light.large_limits(); + assert_eq!(large, Limits { fuel_base: LARGE_FUEL, ..Limits::default() }); + assert_eq!(LARGE_FUEL, 5 * Limits::default().fuel_base); + assert_eq!(light.run_limited(INPUT.as_bytes(), b"{}", &large).unwrap(), INPUT.as_bytes()); + let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#; + let heavy = Plugin::load(&build(&tpl::spinning(heavy, 1, INPUT)), Limits::default()).unwrap(); + assert_eq!(heavy.large_limits(), *heavy.limits()); + assert_eq!((heavy.large_limits().fuel_base, heavy.large_limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS)); +} + #[test] fn an_exporter_returns_its_file_with_an_export_s_budget() { use vectorcraft_plugins::export::{self, Target}; diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index 0c873fd598..fff66aa142 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -190,18 +190,34 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, /// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither, /// transparency and matte; `o.reduction` sets only the distance weights, and `o.colors` is not -/// used. Only the first 255 colors of `palette` are used, leaving room for the transparent entry. -/// Entries no pixel uses are left out. +/// used. Only the first 256 colors of `palette` are used, or the first 255 when a pixel becomes +/// transparent, leaving room for the transparent entry. Entries no pixel uses are left out. pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); - let mut palette: Vec<[u8; 3]> = palette.iter().take(255).copied().collect(); + let has_clear = o.transparency && px.iter().any(|p| p[3] < 128); + let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect(); if palette.is_empty() { palette.push(o.matte.unwrap_or([255; 3])); } finish(px, &colors, width, height, &palette, o, o.dither) } +/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures +/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a +/// pixel that becomes transparent, and for every pixel when `palette` is empty. +pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { + let px = rgba.as_chunks::<4>().0; + let colors = opaque_colors(px, o, false); + let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); + let index = PaletteIndex::new(&pal, o.reduction.weights()); + colors + .iter() + .zip(px) + .map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) }) + .collect() +} + /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> { let matte = o.matte.unwrap_or([255; 3]); diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index 836b5fcf09..d9a8a2fc0f 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -102,11 +102,18 @@ fn a_given_palette_keeps_the_entries_pixels_use() { assert_eq!(ix.transparent, Some(0)); assert_eq!(ix.palette[1..], [[255, 0, 0], [0, 0, 255]], "unused entries left out, the order kept"); assert_eq!(ix.indices, [1, 2, 0, 1]); - // At most 255 of the given colors are used, leaving room for the transparent entry. + // With no transparent pixel all 256 of the given colors can be used; with one, the first 255 + // leave room for the transparent entry. let many: Vec<[u8; 3]> = (0..300u32).map(|i| [(i % 256) as u8, (i / 256) as u8, 0]).collect(); let all = image(256, 2, |x, y| [x as u8, y as u8, 0]); let ix = quantize_to(&all, 256, 2, &o, &many); - assert!(ix.palette.len() <= 255 && ix.palette.iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len()); + assert!(ix.palette.len() == 256 && ix.palette.iter().all(|c| many[..256].contains(c)), "{}", ix.palette.len()); + assert!(ix.palette.contains(&many[255]), "the 256th color is used"); + let mut clear = all.clone(); + clear[3] = 0; + let ix = quantize_to(&clear, 256, 2, &o, &many); + assert_eq!(ix.transparent, Some(0)); + assert!(ix.palette.len() <= 256 && ix.palette[1..].iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len()); } #[test] diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index 10063a5da4..7eb480a414 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -80,14 +80,19 @@ fn lossy_makes_runs_and_smaller_gifs() { let px = image(96, 64, |x, y| [(x * 2 + y) as u8, (y * 3) as u8, ((x * y) % 255) as u8]); let ix = quantize(&px, 96, 64, &PaletteOptions { colors: 64, dither: Dither::Diffusion, ..Default::default() }); let mut lossy_ix = ix.clone(); - lossy(&mut lossy_ix, &px, 80); + lossy(&mut lossy_ix, &px, 80, &[]); let runs = |ix: &Indexed| ix.indices.windows(2).filter(|w| w[0] != w[1]).count(); assert!(runs(&lossy_ix) < runs(&ix)); let size = |ix: &Indexed| gif::encode(ix, false).unwrap().len(); assert!(size(&lossy_ix) < size(&ix), "{} vs {}", size(&lossy_ix), size(&ix)); let mut none = ix.clone(); - lossy(&mut none, &px, 0); + lossy(&mut none, &px, 0, &[]); assert_eq!(none, ix); + // A fixed entry keeps its pixels and takes no others. + let fixed: Vec = (0..ix.palette.len()).filter_map(|i| u8::try_from(i).ok()).collect(); + let mut kept = ix.clone(); + lossy(&mut kept, &px, 100, &fixed); + assert_eq!(kept, ix); } #[test] diff --git a/crates/render/src/encode/web.rs b/crates/render/src/encode/web.rs index 2a26a336d1..3d572cf9ce 100644 --- a/crates/render/src/encode/web.rs +++ b/crates/render/src/encode/web.rs @@ -83,19 +83,24 @@ pub fn to_transparent(ix: &mut Indexed, mapped: impl Fn(usize) -> bool) -> Vec().0; for (row, src) in ix.indices.chunks_mut(w).zip(px.chunks(w)) { for x in 1..row.len() { let (prev, cur) = (row[x - 1], row[x]); - if prev == cur || ix.transparent.is_some_and(|t| t == prev || t == cur) { + if prev == cur || held[usize::from(prev)] || held[usize::from(cur)] { continue; } let (Some(c), Some(p)) = (src.get(x), ix.palette.get(prev as usize)) else { continue }; 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/bounds.rs b/crates/render/src/fx/bounds.rs index dda132308f..2a554a3d92 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -726,6 +726,12 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b let a = art_effects_reach(symbols, n); Some(b.inflate(a, a)) } + // A spine can rotate a blend's keys and steps past their unrotated visual bounds. + NodeKind::Blend { .. } => { + let b = n.reach_bounds_with(symbols)?; + let a = live_content_reach(symbols, n); + vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_blend_effect_bounds(symbols, n)) + } _ => { let b = n.visual_bounds_with(symbols)?; let b = match &n.kind { @@ -804,16 +810,43 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) -> b.inflate(o, o) } -/// `n`'s own visual box, type's grown to hold its glyphs ([`glyphs_box`]): what it draws when its -/// object effects leave it as it is (Revolve builds no art from type). +/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its +/// spine-placed keys and steps: what it draws when its object effects leave it as it is +/// (Revolve builds no art from type). fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { - let b = n.visual_bounds_with(symbols)?; + let b = match &n.kind { + NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_blend_effect_bounds(symbols, n)), + _ => n.visual_bounds_with(symbols), + }?; Some(match &n.kind { NodeKind::Text(t) => vectorcraft_geom::union_opt(Some(b), glyphs_box(t, n.appearance.outset())).unwrap_or(b), _ => b, }) } +/// A rotated blend's effect-bearing content, measured after spine placement. Geometry effects +/// run on the placed shapes, so their reach on the original keys need not cover what they paint. +/// Effect-free blends keep the quick rail envelope without evaluating their steps. +fn placed_blend_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + let NodeKind::Blend { spec, .. } = &n.kind else { return None }; + if spec.orientation != vectorcraft_doc::BlendOrientation::AlignToPath { + return None; + } + let mut has_effects = false; + n.walk(&mut |c| { + has_effects |= has_fx(c) + || has_object_fx(c) + || match &c.kind { + NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol), + _ => false, + }; + }); + if !has_effects { + return None; + } + effects::expand_live(Some(symbols.document()), n).iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, cull_bounds(symbols, c))) +} + /// The box of type `t`'s glyphs as laid out (its layout bounds, else laid out now), grown by its /// characters' strokes, miter spikes included, and by `outset`: on a path they stand above it and /// run past its ends, in an area they can hang past its frame, where its own box 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/export/text.rs b/crates/svg/src/export/text.rs index 8a808b5f72..f8bc712117 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -103,20 +103,23 @@ impl Writer<'_> { || t.stacks_warichu() || (inline && matches!(t.kind, TextKind::OnPath { .. })) || unwritable; - let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t) } else { w.text(n, t) }; + // Every writer below draws this one layout of the type. + let db = vectorcraft_text::FontDb::global(); + let lay = vectorcraft_text::layout(db, t); + let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t, &lay) } else { w.text(n, t, &lay) }; let painted = n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()); // Live type with an inside or outside character stroke writes that stroke apart from the // text, in the group. let apart = !outlined && t.runs.iter().any(|r| aligned(&r.style)); if !painted && !inline && !apart { + #[cfg(test)] + DRAW_HANDED.with(|d| d.set(true)); return chars(self, n); } let id = self.id_attr(n); let a = self.attrs(&css::transparency(n)); self.line(&format!("")); self.depth += 1; - let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut all = lay.to_bezpath(); for (_, bar) in vectorcraft_text::decorations(&lay, db, t) { all.extend(bar.iter()); @@ -154,14 +157,22 @@ impl Writer<'_> { } /// Text as glyph outlines: one compound path per run, painted like the run (gradients span - /// the whole text), over its colour glyphs, as on the canvas. - fn text_outlines(&mut self, n: &Node, t: &TextObject) { + /// the whole text), over its colour glyphs, as on the canvas. `lay` is the layout of `t`. + fn text_outlines(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut runs = vec![kurbo::BezPath::new(); t.runs.len()]; + // Each run's glyphs, in layout order. + let mut run_glyphs = vec![Vec::new(); t.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } // Underline and strikethrough bars join their run's outlines; ruby glyphs are painted // with the run of the text they annotate. - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); for (run, outline) in lay .glyphs .iter() @@ -197,10 +208,10 @@ impl Writer<'_> { // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { + for ((bp, run), glyphs) in runs.iter().zip(&t.runs).zip(&run_glyphs) { // Colour glyphs paint themselves, under their run's paint: bitmap glyphs (emoji) as // their images, COLR and SVG glyphs as their art. - for g in lay.glyphs.iter().filter(|g| g.run == i) { + for g in glyphs { if let Some((image, to_text)) = g.placed_image() { let m = self.matrix(self.xf * to_text); let href = self.blob_href(&image.blob); @@ -233,40 +244,42 @@ impl Writer<'_> { /// spacing come out as on the canvas. Centred and right-aligned lines are anchored /// (`text-anchor`) at their centre or right end, so they stay aligned in a viewer whose font /// differs; other lines are placed where each style run (and, justified, each word) starts. - fn text(&mut self, n: &Node, t: &TextObject) { + /// `lay` is the layout of `t`. + fn text(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { // Live SVG text is written in logical order from left-aligned pieces: bidirectional text // (and right-to-left paragraphs) keep their look as outlines until it is written with // `direction`/`unicode-bidi`. So do runs set Right to Left (Character Direction), whose // `direction="rtl"` would anchor their pieces at the right end. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut again = None; + let lay = handed(t, lay, &mut again); let rtl_runs = t.runs.iter().any(|r| r.style.char_direction == Some(vectorcraft_doc::ParaDirection::RightToLeft)); if lay.glyphs.iter().any(|g| g.rtl) || lay.lines.iter().any(|l| l.rtl) || rtl_runs { self.warn("bidirectional text is outlined to preserve shaping and visual order"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } if let TextKind::OnPath { path, start, end } = &t.kind { // A reader lays a ``'s glyphs straight: joined glyphs bent along the path // keep their look as outlines. if lay.glyphs.iter().any(|g| g.bend.is_some()) { self.warn("joined type bent along a path is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // `` has a start offset only: an end bracket, Align to Path and Spacing // keep their look as outlines. if end.is_some() || t.path_align != vectorcraft_doc::PathAlign::Baseline || t.path_spacing != 0.0 { self.warn("type on a path with an end bracket, Align to Path or Spacing is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A reader turns each `` glyph with the path, as Rainbow does: Skew, 3D // Ribbon, Stair Step and Gravity keep their look as outlines. if t.path_effect != vectorcraft_doc::PathEffect::Rainbow { self.warn("type on a path with an effect other than Rainbow is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // It cannot hang glyphs outside the start bracket either. - if hangs_on_path(t, &lay) { + if hangs_on_path(t, lay) { self.warn("type on a path with glyphs hanging outside its brackets is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // The space before the first character is written as its `dx`; one before a character // after a line break, which the `` writes as a space, keeps its look as outlines. @@ -279,39 +292,39 @@ impl Writer<'_> { }); if spaced_break { self.warn("type on a path with space before a character after a line break is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `` places its characters one after the other: Insert Aki keeps its look as // outlines. if t.runs.iter().any(|r| r.style.aki_left != 0.0 || r.style.aki_right != 0.0) { self.warn("type on a path with Insert Aki is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Tsume does as well. if t.runs.iter().any(|r| r.style.tsume != 0.0) { self.warn("type on a path with Tsume is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Justification…'s Desired word and letter spacing and glyph scaling do too. if (0..t.paragraph_count()).any(|i| !t.layout_justification(t.para_at(i)).desired_is_default()) { self.warn("type on a path with Justification spacing or glyph scaling is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `` holds the characters of the text, not the bullets or numbers drawn // before them. if !lay.markers.is_empty() { self.warn("type on a path with bullets or numbers is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). if !lay.repeat_marks.is_empty() { self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } - return self.text_on_path(n, t, path, *start); + return self.text_on_path(n, t, lay, path, *start); } - self.note_fonts(t, &lay); - let lines = text_lines(t, &lay, self.opts.fewer_tspans); + self.note_fonts(t, lay); + let lines = text_lines(t, lay, self.opts.fewer_tspans); // `drawn` holds the styles the layout draws the text in: Shrink Text to Fit scales its sizes, explicit leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -374,35 +387,36 @@ impl Writer<'_> { } s.push_str(""); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } - /// The inside and outside character strokes of live type `t`, over its text (which goes - /// without them, see [`Self::char_props`]): each such run's stroke on its glyph outlines, drawn - /// twice as wide and clipped or masked to its side as aligned path strokes are + /// The inside and outside character strokes of live type `t`, laid out as `lay`, over its text + /// (which goes without them, see [`Self::char_props`]): each such run's stroke on its glyph + /// outlines, drawn twice as wide and clipped or masked to its side as aligned path strokes are /// ([`Self::side_attr`]). The text stays live; only the stroke follows the outlines. - fn aligned_char_strokes(&mut self, t: &TextObject) { + fn aligned_char_strokes(&mut self, t: &TextObject, lay: &vectorcraft_text::TextLayout) { if !t.runs.iter().any(|r| aligned(&r.style)) { return; } + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); + // Each such run's glyph outlines and then its bars, in layout order. + let mut outlines = vec![BezPath::new(); t.runs.len()]; + for (run, outline) in lay.glyphs.iter().map(|g| (g.run, &g.outline)).chain(bars.iter().map(|(r, b)| (*r, b))) { + if let Some(bp) = outlines.get_mut(run).filter(|_| t.runs.get(run).is_some_and(|r| aligned(&r.style))) { + bp.extend(outline.iter()); + } + } // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, run) in t.runs.iter().enumerate().filter(|(_, r)| aligned(&r.style)) { - let mut bp = BezPath::new(); - for g in lay.glyphs.iter().filter(|g| g.run == i) { - bp.extend(g.outline.iter()); - } - for (_, bar) in bars.iter().filter(|(r, _)| *r == i) { - bp.extend(bar.iter()); - } + for (run, bp) in t.runs.iter().zip(&outlines).filter(|(r, _)| aligned(&r.style)) { if bp.elements().is_empty() { continue; } - let pd = PathData::from_bezpath(&bp); + let pd = PathData::from_bezpath(bp); let ap = vectorcraft_doc::Appearance { items: vec![AppearanceItem::Stroke(run.style.stroke_layer())], ..Default::default() }; let d = self.path_d(&pd, self.xf); self.shape(&Node::path(NodeId(u64::MAX), pd.clone(), ap), &d, None, &[&pd], FillRule::NonZero, Some(lay.bounds)); @@ -574,15 +588,16 @@ impl Writer<'_> { rules } - /// Type on a path: a `` along the path (a def). - fn text_on_path(&mut self, n: &Node, t: &TextObject, path: &PathData, start: f64) { + /// Type on a path, laid out as `lay`: a `` along the path (a def). + fn text_on_path(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout, path: &PathData, start: f64) { let id = self.id_attr(n); let pid = self.fresh_id("text-path"); let d = self.path_d(path, self.xf * t.xf); self.def(1, &format!("")); // The element's user space is the document's; gradients span the laid-out text. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - self.note_fonts(t, &lay); + let mut again = None; + let lay = handed(t, lay, &mut again); + self.note_fonts(t, lay); // The styles the layout draws the text in: Dynamic Text scales its sizes, leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -626,7 +641,7 @@ impl Writer<'_> { } s.push_str(""); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } } @@ -635,6 +650,34 @@ fn aligned(st: &CharStyle) -> bool { st.has_stroke() && st.stroke_align != StrokeAlign::Center } +#[cfg(test)] +thread_local! { + /// Tests: each type writer lays `t` out again ([`handed`]) instead of drawing the layout it is + /// handed, so a test can compare the two. The first writer of type written without a group + /// still draws the layout it is handed ([`DRAW_HANDED`]), so each object is laid out where it + /// is drawn. + static LAY_OUT_AGAIN: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: the next type writer draws the layout it is handed, with [`LAY_OUT_AGAIN`] too. + static DRAW_HANDED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The layout a type writer draws: `lay`, the layout of `t` it is handed. In tests that ask for it, +/// `t` laid out again, kept in `again`. +fn handed<'a>( + t: &TextObject, + lay: &'a vectorcraft_text::TextLayout, + again: &'a mut Option, +) -> &'a vectorcraft_text::TextLayout { + #[cfg(test)] + let lay = { + let draw_handed = DRAW_HANDED.with(|d| d.replace(false)); + if LAY_OUT_AGAIN.with(std::cell::Cell::get) && !draw_handed { &*again.insert(vectorcraft_text::layout(FontDb::global(), t)) } else { lay } + }; + #[cfg(not(test))] + let _ = (t, again); + lay +} + /// Does type on a path `t`, laid out as `lay`, hang glyphs outside its brackets? It does when /// Optical Margin Alignment or its first paragraph's Roman Hanging Punctuation is on and its /// glyphs sit elsewhere with both off. diff --git a/crates/svg/src/export/text/tests.rs b/crates/svg/src/export/text/tests.rs index 951817c2c5..6b2fcbfb1f 100644 --- a/crates/svg/src/export/text/tests.rs +++ b/crates/svg/src/export/text/tests.rs @@ -1,5 +1,7 @@ //! The advances a reader gives live type ([`reader_advances`]): the same as when the type is laid //! out again each time, which happens only when a reader sets the type differently from its layout. +//! The type writers draw one layout of the type ([`handed`]) and write what laying it out in each +//! writer writes. use super::*; use vectorcraft_doc::text::{Bullet, ParaList}; @@ -145,3 +147,202 @@ fn a_mixed_document_lays_out_again_only_the_japanese_type() { let (svg, again) = export_layouts_again(vec![point("Latin"), point("「かな」。"), point(""), point("Ab2")]); assert_eq!(again, 1, "{svg}"); } + +/// Type `t`, with the object's own fills and strokes `items`, alone in a document. +fn doc_of(t: TextObject, items: Vec) -> Document { + let mut d = Document::new(300.0, 200.0); + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +/// Type on a straight path across the page. +fn on_path(text: &str, st: CharStyle) -> TextObject { + let mut t = TextObject::point(Point::ZERO, text, st); + let mut line = BezPath::new(); + line.move_to((20.0, 100.0)); + line.line_to((280.0, 100.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + t +} + +/// A character style with a stroke on side `align`. +fn stroked(align: StrokeAlign) -> CharStyle { + CharStyle { stroke: Paint::solid(vectorcraft_color::Color::rgb8(200, 0, 0)), stroke_width: 2.0, stroke_align: align, ..style() } +} + +fn red_fill() -> Vec { + vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0))))] +} + +/// The type the writers handle differently, each with how many times its export lays the type +/// out: once, plus the layout of the copy that checks for hanging glyphs on a path; and how many +/// times with each writer laying the type out on its own ([`LAY_OUT_AGAIN`]). +fn writer_cases() -> Vec<(&'static str, Document, crate::ExportOptions, u64, u64)> { + let opts = crate::ExportOptions::default; + let outlined = || crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }; + let mut runs = point("Red "); + runs.runs.push(TextRun::new("green ", CharStyle { underline: true, ..stroked(StrokeAlign::Outside) })); + runs.runs.push(TextRun::new("blue", CharStyle { strikethrough: true, ..style() })); + let mut many = point(""); + many.runs = (0..200).map(|i| TextRun::new(if i % 7 == 6 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 5), ..style() })).collect(); + let mut rtl_run = point("abc"); + rtl_run.runs[0].style.char_direction = Some(vectorcraft_doc::ParaDirection::RightToLeft); + let mut skewed = on_path("Skewed", style()); + skewed.path_effect = vectorcraft_doc::PathEffect::Skew; + let mut hanging = on_path("\u{201C}Quoted.\u{201D}", style()); + hanging.optical_margin = true; + let mut inside = point("Inside out"); + inside.runs.push(TextRun::new(" plain", style())); + inside.runs[0].style = CharStyle { underline: true, ..stroked(StrokeAlign::Inside) }; + let outside = TextObject::point(Point::new(20.0, 20.0), "Outside", stroked(StrokeAlign::Outside)); + vec![ + ("point type", doc_of(point("Plain type"), vec![]), opts(), 1, 1), + ("point type with a fill", doc_of(point("Filled type"), red_fill()), opts(), 1, 2), + ("type on a path", doc_of(on_path("Type on a path", style()), vec![]), opts(), 1, 2), + ("type on a path with a fill", doc_of(on_path("Filled path type", style()), red_fill()), opts(), 1, 3), + ("bidirectional type", doc_of(point("abc \u{5D0}\u{5D1}\u{5D2} def"), vec![]), opts(), 1, 2), + ("a run set right to left", doc_of(rtl_run, vec![]), opts(), 1, 2), + ("bidirectional type on a path", doc_of(on_path("abc \u{5D0}\u{5D1}\u{5D2}", style()), vec![]), opts(), 1, 2), + ("type on a path with Skew", doc_of(skewed, vec![]), opts(), 1, 2), + ("type on a path that may hang", doc_of(hanging, vec![]), opts(), 2, 3), + ("outside character stroke", doc_of(outside, vec![]), opts(), 1, 3), + ("inside character stroke", doc_of(inside, vec![]), opts(), 1, 3), + ("runs with a stroke and decorations", doc_of(runs.clone(), vec![]), opts(), 1, 3), + ("runs as outlines", doc_of(runs.clone(), vec![]), outlined(), 1, 1), + ("outside stroke on a path with a fill", doc_of(on_path("Stroked", stroked(StrokeAlign::Outside)), red_fill()), opts(), 1, 4), + ("inside stroke on a path", doc_of(on_path("Stroked", stroked(StrokeAlign::Inside)), vec![]), opts(), 1, 4), + ("many runs as outlines", doc_of(many.clone(), vec![]), outlined(), 1, 1), + ("many runs", doc_of(many, vec![]), opts(), 1, 1), + ] +} + +/// SVG export of `d` with each type writer laying the type out again (`again`) or drawing the +/// layout it is handed, and how many times the export laid type out. +fn export_counting(d: &Document, opts: &crate::ExportOptions, again: bool) -> (crate::Output, u64) { + LAY_OUT_AGAIN.with(|a| a.set(again)); + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let out = crate::export_full(d, opts, None); + let laid = vectorcraft_text::test_fonts::layouts_on_this_thread() - before; + LAY_OUT_AGAIN.with(|a| a.set(false)); + (out, laid) +} + +#[test] +fn every_type_writer_draws_one_layout() { + for (name, d, opts, layouts, own_layouts) in writer_cases() { + let (out, laid) = export_counting(&d, &opts, false); + assert_eq!(laid, layouts, "{name}: {}", out.svg); + // The same file and warnings as each writer laying the type out on its own. + let (again, laid_again) = export_counting(&d, &opts, true); + assert_eq!(laid_again, own_layouts, "{name}"); + assert_eq!(out.svg, again.svg, "{name}"); + assert_eq!(out.warnings, again.warnings, "{name}"); + assert_eq!(out.setting_notes, again.setting_notes, "{name}"); + } +} + +/// The CPU time this thread has run, from Linux's scheduler statistics; wall time elsewhere. +fn thread_time(start: std::time::Instant) -> std::time::Duration { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next()?.parse().ok()) + .map_or_else(|| start.elapsed(), std::time::Duration::from_nanos) +} + +fn median(mut v: Vec) -> std::time::Duration { + v.sort(); + v[v.len() / 2] +} + +/// Timing, not a check: SVG export of a large document with each writer laying the type out again +/// and with one layout handed to them, alternating, seven runs each; and grouping the glyphs of +/// type with 1,000 runs by run, one filter per run against one pass. Run with +/// `cargo test --release -p vectorcraft-svg --lib svg_type_layout_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing"] +fn svg_type_layout_timing() { + let mut d = Document::new(2000.0, 2000.0); + let l = d.layers[0].id; + let add = |d: &mut Document, t: TextObject, items: Vec| { + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + d.insert(Some(l), usize::MAX, n).unwrap(); + }; + let words: String = "Type set along a path for timing. ".chars().cycle().take(60).collect(); + for _ in 0..1000 { + add(&mut d, on_path(&words, style()), vec![]); + } + let hebrew = "abc \u{5D0}\u{5D1}\u{5D2}\u{5D3} def ".repeat(6); + for _ in 0..1000 { + add(&mut d, point(&hebrew.chars().take(80).collect::()), vec![]); + } + for _ in 0..300 { + add(&mut d, TextObject::point(Point::new(20.0, 20.0), "Stroked outside", stroked(StrokeAlign::Outside)), vec![]); + } + let mut runs = point(""); + runs.runs = (0..1000).map(|i| TextRun::new(if i % 9 == 8 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 3), ..style() })).collect(); + let mut outlined = Document::new(2000.0, 2000.0); + let ol = outlined.layers[0].id; + for _ in 0..300 { + let n = Node::new(outlined.alloc_id(), NodeKind::Text(Box::new(runs.clone()))); + outlined.insert(Some(ol), usize::MAX, n).unwrap(); + } + let docs = [ + ("1,000 on a path, 1,000 bidirectional, 300 outside strokes", &d, crate::ExportOptions::default()), + ("300 texts of 1,000 runs as outlines", &outlined, crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }), + ]; + for (name, doc, opts) in docs { + let (one, again) = (export_counting(doc, &opts, false), export_counting(doc, &opts, true)); + assert_eq!(one.0.svg, again.0.svg, "{name}"); + let (mut base, mut handed) = (vec![], vec![]); + for _ in 0..7 { + for (again, times) in [(true, &mut base), (false, &mut handed)] { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + let _ = export_counting(doc, &opts, again); + times.push(thread_time(start) - t0); + } + } + let (from, to, base_median, handed_median) = (again.1, one.1, median(base.clone()), median(handed.clone())); + println!( + "{name}: layouts {from} -> {to}; laid out again {base:?} (median {base_median:?}); one layout {handed:?} (median {handed_median:?})" + ); + } + // The glyphs of one 1,000-run text, grouped by run 300 times. + let lay = vectorcraft_text::layout(FontDb::global(), &runs); + let (mut filtered, mut bucketed) = (vec![], vec![]); + for _ in 0..7 { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + for i in 0..runs.runs.len() { + for g in lay.glyphs.iter().filter(|g| g.run == i) { + std::hint::black_box(g); + } + } + } + filtered.push(thread_time(start) - t0); + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + let mut run_glyphs = vec![Vec::new(); runs.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } + for g in run_glyphs.iter().flatten() { + std::hint::black_box(g); + } + } + bucketed.push(thread_time(start) - t0); + } + println!( + "grouping 300 texts of 1,000 runs: filter per run {filtered:?} (median {:?}); one pass {bucketed:?} (median {:?})", + median(filtered.clone()), + median(bucketed.clone()) + ); +} diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index aaeac31a11..5e7afdd55a 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -208,6 +208,7 @@ pub(crate) fn import_finding( blends: fx::blends(&xml, &scan.markers), filter_sources: fx::sources(&xml, &scan.markers, |h| files.data_href(h)), files, + image_keys: HashMap::new(), non_scaling: found.non_scaling, data: found.data, events: found.events, @@ -371,6 +372,9 @@ struct Importer { filter_sources: HashMap, /// The files `` elements link to. files: files::Files, + /// The image key of each raster image usvg got, by the address of its bytes, with the bytes + /// held so that the address isn't given to other bytes during the import. + image_keys: HashMap>, String)>, /// Ids of the shapes whose strokes don't scale ([`vector_effect`]). non_scaling: HashSet, /// The `data-*` attributes of elements, by id ([`user_data`]). diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index c1dd856559..7cf350e5e1 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -780,6 +780,7 @@ impl Importer { usvg::ImageKind::WEBP(d) => (d, "image/webp"), usvg::ImageKind::SVG(tree) => return self.svg_image(tree, acc), }; + let source = bytes; let size = i.size(); let (pw, ph) = vectorcraft_doc::header_size(bytes).unwrap_or((size.width().round().max(1.0) as u32, size.height().round().max(1.0) as u32)); // A turned CMYK image is stored as the CMYK TIFF of its inks, the size of the PNG usvg got. @@ -792,10 +793,7 @@ impl Importer { let linked = self.files.linked(i.kind()); let missing = linked.is_some_and(|l| l.missing); let link = linked.map(|l| l.link.clone()); - let key = match &link { - Some(l) => linked_key(bytes, &l.path), - None => format!("img-{:016x}", fnv1a(bytes)), - }; + let key = self.image_key(source, bytes, link.as_ref().map(|l| l.path.as_str())); self.doc.images.entry(key.clone()).or_insert_with(|| { let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()) }; if link.is_some() && !missing { blob.with_proxy() } else { blob } @@ -813,6 +811,29 @@ impl Importer { Some(node) } + /// The image key of the raster image usvg got as `source`, stored as `bytes` (the CMYK TIFF + /// that replaces a turned CMYK image, else `source`), linked to `path` when it is linked. The + /// bytes are hashed for the first image that shows `source`; the images after it that show + /// the same bytes get the key kept for it. + fn image_key(&mut self, source: &Arc>, bytes: &[u8], path: Option<&str>) -> String { + let at = Arc::as_ptr(source) as usize; + #[cfg(test)] + let kept = !tests::UNKEPT.get(); + #[cfg(not(test))] + let kept = true; + if kept && let Some((_, key)) = self.image_keys.get(&at) { + return key.clone(); + } + #[cfg(test)] + tests::IMAGE_HASHES.set(tests::IMAGE_HASHES.get() + 1); + let key = match path { + Some(path) => linked_key(bytes, path), + None => format!("img-{:016x}", fnv1a(bytes)), + }; + self.image_keys.insert(at, (source.clone(), key.clone())); + key + } + /// An SVG shown as an image (a data URL or a linked file) → its art, `acc` mapping its size. /// Its ids are its own: they mean nothing in the SVG around it. fn svg_image(&mut self, tree: &usvg::Tree, acc: Affine) -> Option { @@ -870,6 +891,7 @@ mod tests { blends: HashMap::new(), filter_sources: HashMap::new(), files: Files::default(), + image_keys: HashMap::new(), non_scaling: HashSet::new(), data: HashMap::new(), events: HashMap::new(), @@ -891,4 +913,242 @@ mod tests { assert!(matches!(im.error, Some(SvgError::TooManyImages(crate::MAX_NESTED_SVG_IMAGES)))); assert_eq!(im.error.unwrap().to_string(), "the SVG expands to more than 256 nested SVG images"); } + + thread_local! { + /// How many times this thread's imports hashed an image's bytes for its key. + pub(super) static IMAGE_HASHES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// When set, this thread's imports hash the bytes of every image for its key, without + /// the keys kept for earlier images. + pub(super) static UNKEPT: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// `svg` imported on this thread with `opts`, with image keys kept or not, and how many times + /// image bytes were hashed for keys. + fn import_counting(svg: &str, opts: &crate::ImportOptions, kept: bool) -> (Document, Vec, usize) { + UNKEPT.set(!kept); + IMAGE_HASHES.set(0); + let imported = crate::import::import(svg, opts, crate::MAX_NODES); + UNKEPT.set(false); + let (doc, warnings) = imported.unwrap(); + (doc, warnings, IMAGE_HASHES.get()) + } + + /// The image objects of `doc` in paint order. + fn image_objects(doc: &Document) -> Vec { + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((**im).clone()); + } + }); + out + } + + fn svg_of(body: &str) -> String { + format!(r#"{body}"#) + } + + /// A `w` × `h` PNG of pixels made from `seed`. + fn png(w: u32, h: u32, seed: u32) -> Vec { + let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1); + let img = image::RgbaImage::from_fn(w, h, |_, _| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let [r, g, b, _] = state.to_le_bytes(); + image::Rgba([r, g, b, 255]) + }); + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + fn data_url(mime: &str, bytes: &[u8]) -> String { + format!("data:{mime};base64,{}", crate::base64_encode(bytes)) + } + + /// A little-endian, uncompressed 1 × 1 CMYK TIFF of the inks `cmyk`. + fn cmyk_tiff(cmyk: [u8; 4]) -> Vec { + let entry = |tag: u16, kind: u16, count: u32, value: u32| { + [&tag.to_le_bytes()[..], &kind.to_le_bytes(), &count.to_le_bytes(), &value.to_le_bytes()].concat() + }; + let entries = 11u16; + let bits_at = 8 + 2 + u32::from(entries) * 12 + 4; + let data_at = bits_at + 8; + let mut out = [b"II".as_slice(), &[0x2a, 0], &8u32.to_le_bytes(), &entries.to_le_bytes()].concat(); + for e in [ + entry(256, 4, 1, 1), + entry(257, 4, 1, 1), + entry(258, 3, 4, bits_at), + entry(259, 3, 1, 1), + entry(262, 3, 1, 5), + entry(273, 4, 1, data_at), + entry(274, 3, 1, 1), + entry(277, 3, 1, 4), + entry(278, 4, 1, 1), + entry(279, 4, 1, 4), + entry(284, 3, 1, 1), + ] { + out.extend(e); + } + out.extend(0u32.to_le_bytes()); + for _ in 0..4 { + out.extend(8u16.to_le_bytes()); + } + assert_eq!(out.len(), data_at as usize); + out.extend(cmyk); + out + } + + /// `svg` imported with `opts` hashes image bytes `hashes` times for keys, and once for each + /// image without kept keys; both imports give the same document and warnings. + fn same_as_hashing_every_image(svg: &str, opts: &crate::ImportOptions, hashes: usize) -> (Document, Vec) { + let (doc, warnings, n) = import_counting(svg, opts, true); + let (every, every_warnings, every_n) = import_counting(svg, opts, false); + assert_eq!(every_n, image_objects(&every).len(), "without kept keys, each image is hashed"); + assert_eq!(n, hashes, "image bytes hashed for keys"); + assert_eq!(warnings, every_warnings); + assert_eq!(image_objects(&doc), image_objects(&every), "the same image objects"); + assert_eq!(doc.images, every.images, "the same stored images"); + assert!(doc == every, "the same document"); + (doc, warnings) + } + + /// Every `` of one image, and every `` with the same data URL, shows bytes usvg + /// got once: they are hashed once, and every image has the key of the image's bytes. + #[test] + fn an_image_shown_many_times_is_hashed_once() { + let png = png(3, 2, 1); + let href = data_url("image/png", &png); + let uses: String = (0..6).map(|i| format!(r##""##, i * 10)).collect(); + let inline: String = (0..6).map(|i| format!(r#""#, i * 10)).collect(); + for body in [format!(r#"{uses}"#), inline] { + let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1); + assert!(warnings.is_empty(), "{warnings:?}"); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 6); + let key = format!("img-{:016x}", fnv1a(&png)); + assert!(objects.iter().all(|o| o.key == key && o.link.is_none() && (o.width, o.height) == (3, 2)), "{objects:?}"); + assert_eq!(doc.images.keys().collect::>(), [&key]); + assert_eq!((doc.images[&key].mime.as_str(), &**doc.images[&key].bytes, doc.images[&key].proxy.is_none()), ("image/png", &png[..], true)); + } + } + + /// One image is hashed once; two images of different bytes twice, with keys of their own; two + /// data URLs written differently that hold the same bytes are hashed once each, and share the + /// key and the stored image of those bytes. + #[test] + fn each_buffer_of_image_bytes_is_hashed_once() { + let (a, b) = (png(2, 2, 1), png(2, 2, 2)); + let image = |href: &str| format!(r#""#); + let opts = crate::ImportOptions::default(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&image(&data_url("image/png", &a))), &opts, 1); + assert_eq!(image_objects(&doc)[0].key, format!("img-{:016x}", fnv1a(&a))); + let two = [image(&data_url("image/png", &a)), image(&data_url("image/png", &b)), image(&data_url("image/png", &a))].concat(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&two), &opts, 2); + let keys: Vec = image_objects(&doc).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&b)), format!("img-{:016x}", fnv1a(&a))]); + assert_eq!(doc.images.len(), 2); + let spelled = [image(&data_url("image/png", &a)), image(&data_url("image/png;x=y", &a))].concat(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&spelled), &opts, 2); + let keys: Vec = image_objects(&doc).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&a))]); + assert_eq!(doc.images.len(), 1); + } + + /// Every image of one linked file, or of one missing file, is hashed once: the file is read + /// once, and every image has the key of its bytes and its path, with its link. + #[test] + fn a_linked_or_missing_file_shown_many_times_is_hashed_once() { + let png = png(4, 2, 3); + let reads = std::sync::atomic::AtomicUsize::new(0); + let read = |path: &str| { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + path.ends_with("a.png").then(|| (png.clone(), vectorcraft_doc::LinkInfo::new(path))) + }; + let opts = crate::ImportOptions { folder: Some("/f"), read: Some(&read) }; + for (name, missing) in [("a.png", false), ("gone.png", true)] { + let body: String = (0..5).map(|i| format!(r#""#, i * 10)).collect(); + reads.store(0, std::sync::atomic::Ordering::Relaxed); + let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &opts, 1); + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2, "{name}: one read for each of the two imports"); + assert_eq!(warnings.iter().any(|w| w.contains(name)), missing, "{name}: {warnings:?}"); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 5); + let path = objects[0].link.as_ref().expect("linked").path.clone(); + assert!(path.ends_with(name), "{path}"); + let stored = doc.images[&objects[0].key].clone(); + assert_eq!(objects[0].key, linked_key(&stored.bytes, &path), "{name}"); + assert!(objects.iter().all(|o| o.key == objects[0].key && o.link.as_ref().is_some_and(|l| l.path == path)), "{name}"); + assert_eq!(doc.images.len(), 1); + assert_eq!(*stored.bytes == png, !missing, "{name}: the file's bytes, or a placeholder"); + assert_eq!(stored.is_proxy(), missing, "{name}"); + } + } + + /// A CMYK TIFF shown many times is stored as a CMYK TIFF and hashed once, its key that of the + /// stored TIFF. + #[test] + fn a_cmyk_image_shown_many_times_is_hashed_once() { + let tif = cmyk_tiff([255, 0, 0, 0]); + let href = data_url("image/tiff", &tif); + let uses: String = (0..4).map(|i| format!(r##""##, i * 10)).collect(); + let body = format!(r#"{uses}"#); + let (doc, _) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 4); + let blob = &doc.images[&objects[0].key]; + assert_eq!(blob.mime, "image/tiff"); + assert!(blob.cmyk().is_some(), "stored with its inks"); + assert_eq!(objects[0].key, format!("img-{:016x}", fnv1a(&blob.bytes))); + assert!(objects.iter().all(|o| o.key == objects[0].key)); + } + + /// This thread's CPU time in seconds where the system reports it, else the time since a first + /// call. + fn cpu_seconds() -> f64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + Some(ns) => ns / 1e9, + None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(), + } + } + + /// The import's time for one PNG data URL shown by many `` elements, hashing every image + /// and keeping keys alternating in one process: `cargo test --release -p vectorcraft-svg --lib + /// importer::tests::image_key_timing -- --ignored --nocapture`. + #[test] + #[ignore = "timing, run by hand"] + fn image_key_timing() { + for (side, uses) in [(512, 100), (1024, 500)] { + let png = png(side, side, 7); + let refs: String = (0..uses).map(|i| format!(r##""##, i % 20, i / 20)).collect(); + let svg = svg_of(&format!(r#"{refs}"#, data_url("image/png", &png))); + let run = |kept: bool| { + let t = cpu_seconds(); + let (doc, _, _) = import_counting(&svg, &crate::ImportOptions::default(), kept); + let spent = cpu_seconds() - t; + assert_eq!(image_objects(&doc).len(), uses); + spent + }; + run(false); + run(true); + let (mut every, mut kept) = (vec![], vec![]); + for round in 0..7 { + if round % 2 == 0 { + every.push(run(false)); + kept.push(run(true)); + } else { + kept.push(run(true)); + every.push(run(false)); + } + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::>().join(" "); + println!("{uses} uses of a {} byte PNG: every image {} ms, kept {} ms", png.len(), ms(&every), ms(&kept)); + println!("{uses} uses: median every image {:.1} ms, kept {:.1} ms", median(&mut every) * 1e3, median(&mut kept) * 1e3); + } + } } 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/svg/tests/it/effects_export.rs b/crates/svg/tests/it/effects_export.rs index c1a19e8d53..9a0f2aaeba 100644 --- a/crates/svg/tests/it/effects_export.rs +++ b/crates/svg/tests/it/effects_export.rs @@ -145,3 +145,52 @@ fn geometry_effects_on_type_export_as_its_reshaped_outlines() { assert!(!svg.contains(") { + use vectorcraft_doc::AppearanceItem; + let solid = |p: &Paint, r: f32, g: f32, b: f32| matches!(p, Paint::Solid { color, .. } if *color == Color::rgb(r, g, b)); + for i in &n.appearance.items { + let mark = match i { + AppearanceItem::Fill(f) if solid(&f.paint, 0.0, 0.0, 1.0) => 'b', + AppearanceItem::Fill(f) if solid(&f.paint, 1.0, 0.0, 0.0) => 'r', + AppearanceItem::Stroke(s) if s.width > 0.0 && solid(&s.paint, 0.0, 1.0, 0.0) => 'g', + _ => continue, + }; + if out.last() != Some(&(mark, clipped)) { + out.push((mark, clipped)); + } + } + let clips = matches!(n.kind, NodeKind::Group { clip: true, .. }); + for c in n.children().into_iter().flatten().skip(usize::from(clips)) { + painted_order(c, clipped || clips, out); + } +} + +#[test] +fn painted_clipping_type_exports_with_group_effect() { + // Type filled blue and stroked green clips a red square in a group with an Offset Path effect: + // the SVG paints the type's fill inside the clip behind the square, and its stroke over the + // clipped art, outside the clip. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let style = CharStyle { size: 40.0, fill: blue, stroke: green, stroke_width: 2.0, ..Default::default() }; + let mut d = Document::new(200.0, 200.0); + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), red); + let clip = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(text), std::sync::Arc::new(square)], clip: true }); + let mut outer = Node::group(d.alloc_id(), vec![std::sync::Arc::new(clip)]); + outer.appearance.effects.push(Effect { params: json!({"offset": 1}), ..fx("path.offsetPath") }); + let l = d.layers[0].id; + d.insert(Some(l), 0, outer).unwrap(); + let svg = export(&d, &ExportOptions::default()); + let back = vectorcraft_svg::import(&svg).unwrap_or_else(|e| panic!("{e}: {svg}")); + let mut order = vec![]; + for layer in &back.layers { + painted_order(layer, false, &mut order); + } + assert_eq!(order, [('b', true), ('r', true), ('g', false)], "{svg}"); +} 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/build.rs b/crates/text/build.rs index 412c471c11..5402ddbe07 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -125,16 +125,19 @@ fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { missing.push(format!("{} {}", e.family, e.style)); continue; }; - let (Some(file), Some(sha)) = (row.get(2), row.get(6)) else { + let (Some(file), Some(scripts), Some(sha)) = (row.get(2), row.get(3), row.get(6)) else { return Err(format!("malformed manifest row for {} {}", e.family, e.style)); }; let integrity = web_fonts::sri(sha).ok_or_else(|| format!("bad sha256 for {} {}", e.family, e.style))?; + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, - " WebFont {{ family: {:?}, style: {:?}, startup: {}, url: {:?}, integrity: {:?} }},", + " WebFont {{ family: {:?}, style: {:?}, startup: {}, demand: {}, scripts: &[{}], url: {:?}, integrity: {:?} }},", e.family, e.style, e.startup, + e.demand, + scripts.join(", "), web_fonts::url(sha, file), integrity, ); diff --git a/crates/text/build/web_fonts.rs b/crates/text/build/web_fonts.rs index ccd387afab..ac58913afc 100644 --- a/crates/text/build/web_fonts.rs +++ b/crates/text/build/web_fonts.rs @@ -5,8 +5,11 @@ /// One line of `web-fonts.txt`: `when | family | style`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Listed<'a> { - /// `startup` (fetched before the app starts) rather than `background`. + /// `startup` (fetched before the app starts). pub startup: bool, + /// `demand` (fetched when the interface needs a character of one of the face's scripts). + /// Neither this nor `startup`: `background`. + pub demand: bool, pub family: &'a str, pub style: &'a str, } @@ -23,15 +26,16 @@ pub fn parse_list(text: &str) -> Result>, String> { let [when, family, style] = fields.as_slice() else { return Err(format!("web-fonts.txt line {}: expected `when | family | style`", i + 1)); }; - let startup = match *when { - "startup" => true, - "background" => false, - other => return Err(format!("web-fonts.txt line {}: `{other}` is neither startup nor background", i + 1)), + let (startup, demand) = match *when { + "startup" => (true, false), + "background" => (false, false), + "demand" => (false, true), + other => return Err(format!("web-fonts.txt line {}: `{other}` is not startup, background or demand", i + 1)), }; if family.is_empty() || style.is_empty() { return Err(format!("web-fonts.txt line {}: empty family or style", i + 1)); } - out.push(Listed { startup, family, style }); + out.push(Listed { startup, demand, family, style }); } Ok(out) } @@ -105,12 +109,14 @@ mod tests { #[test] fn list_parsing() { - let l = parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\n").unwrap(); + let l = + parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\ndemand | NanumGothic | Regular\n").unwrap(); assert_eq!( l, [ - Listed { startup: true, family: "Noto Sans Arabic", style: "Regular" }, - Listed { startup: false, family: "Amiri", style: "Bold Italic" } + Listed { startup: true, demand: false, family: "Noto Sans Arabic", style: "Regular" }, + Listed { startup: false, demand: false, family: "Amiri", style: "Bold Italic" }, + Listed { startup: false, demand: true, family: "NanumGothic", style: "Regular" } ] ); assert!(parse_list("soon | A | B").unwrap_err().contains("line 1")); diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index b15b77ec72..24eef3de40 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -19,8 +19,13 @@ pub struct CraftFont { pub struct WebFont { pub family: &'static str, pub style: &'static str, - /// Fetched before the app starts (a fallback the first frame needs), else in the background. + /// Fetched before the app starts (a fallback the first frame needs). pub startup: bool, + /// Fetched only when the interface needs a character of one of [`WebFont::scripts`] (see + /// [`demand_fonts`]). With neither this nor `startup`, fetched in the background. + pub demand: bool, + /// ISO 15924 scripts the face is for (its craft-fonts manifest row), e.g. `"Hang"`. + pub scripts: &'static [&'static str], /// Site-relative URL, `fonts//`. pub url: &'static str, /// Subresource Integrity value, `sha256-`; the browser rejects other bytes. @@ -106,10 +111,65 @@ pub fn japanese_ui_fonts(bold: bool) -> Vec<&'static CraftFont> { v } +/// The script of `c` that a `demand` web face is fetched for: `"Hang"` for Hangul (jamo, +/// compatibility jamo, syllables and the halfwidth forms) and `"Deva"` for Devanagari (with its +/// extended blocks and the Vedic extensions). `None` for every other character. +pub fn demand_script(c: char) -> Option<&'static str> { + match c as u32 { + 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xFFA0..=0xFFDC => Some("Hang"), + 0x0900..=0x097F | 0x1CD0..=0x1CFF | 0xA8E0..=0xA8FF | 0x11B00..=0x11B5F => Some("Deva"), + _ => None, + } +} + +/// The indexes in `fonts` of the `demand` faces for the scripts of `chars` (by +/// [`demand_script`]), each once, in `fonts` order. +pub fn demand_fonts(fonts: &[WebFont], chars: impl IntoIterator) -> Vec { + let mut scripts: Vec<&str> = Vec::new(); + for s in chars.into_iter().filter_map(demand_script) { + if !scripts.contains(&s) { + scripts.push(s); + } + } + fonts.iter().enumerate().filter(|(_, f)| f.demand && f.scripts.iter().any(|s| scripts.contains(s))).map(|(i, _)| i).collect() +} + #[cfg(test)] mod tests { use super::*; + fn web_font(family: &'static str, startup: bool, demand: bool, scripts: &'static [&'static str]) -> WebFont { + WebFont { family, style: "Regular", startup, demand, scripts, url: "", integrity: "" } + } + + #[test] + fn demand_scripts_of_hangul_and_devanagari() { + for c in ['한', '국', 'ㄱ', 'ᄀ', 'ᄀ'] { + assert_eq!(demand_script(c), Some("Hang"), "{c}"); + } + for c in ['ह', 'ि', '्', '़', '।', '\u{A8F2}'] { + assert_eq!(demand_script(c), Some("Deva"), "{c}"); + } + for c in ['A', 'é', 'ا', 'ก', 'ა', '日', 'ロ', '中'] { + assert_eq!(demand_script(c), None, "{c}"); + } + } + + #[test] + fn demand_fonts_follow_the_scripts_painted() { + let fonts = [ + web_font("Arabic", true, false, &["Arab"]), + web_font("Picked", false, false, &["Hang"]), + web_font("Korean", false, true, &["Hang", "Kore"]), + web_font("Devanagari", false, true, &["Deva"]), + ]; + assert_eq!(demand_fonts(&fonts, "한국어".chars()), [2], "Korean fetches only the Korean face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी".chars()), [3], "Hindi fetches only the Devanagari face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी 한국어 Layer".chars()), [2, 3], "each once, in list order"); + assert!(demand_fonts(&fonts, "English العربية 日本語".chars()).is_empty(), "other scripts fetch nothing"); + assert!(demand_fonts(&[], "한국어".chars()).is_empty(), "built without craft-fonts: nothing to fetch"); + } + #[test] fn document_fonts_keep_script_priority_and_include_every_face_once() { let font = |family, style, scripts| CraftFont { family, style, scripts, bytes: &[] }; @@ -157,7 +217,9 @@ mod tests { .collect(); assert_eq!(WEB_FONTS.len(), listed.len()); for (l, w) in listed.iter().zip(WEB_FONTS) { - assert_eq!((l.family, l.style, l.startup), (w.family, w.style, w.startup)); + assert_eq!((l.family, l.style, l.startup, l.demand), (w.family, w.style, w.startup, w.demand)); + let face = CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style); + assert_eq!(face.map(|f| f.scripts), Some(w.scripts), "{} {}: the manifest's scripts", w.family, w.style); let (dir, name) = w.url.strip_prefix("fonts/").and_then(|r| r.split_once('/')).unwrap(); assert!(dir.len() == 16 && dir.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), "{}", w.url); assert!(name.ends_with(".ttf") || name.ends_with(".otf"), "{}", w.url); @@ -169,5 +231,11 @@ mod tests { let expected: Vec<_> = ["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); assert_eq!(startup, expected); + // Korean and Devanagari faces are fetched only on demand, never at startup or in the + // background queue every session runs. + let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect(); + let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); + assert_eq!(demand, expected); + assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand))); } } 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/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 1e1a195db0..7a2a23f089 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1505,6 +1505,19 @@ fn remapped_source_sans(family: &str, postscript: &str, mapping: &[(char, char)] Some(builder.build()) } +/// The family of [`private_use_font`]. +pub const PRIVATE_USE_FAMILY: &str = "Private Use Sans"; + +/// The character [`private_use_font`] maps: the first code point of Supplementary Private Use +/// Area-A, which no bundled or craft-fonts face covers. +pub const PRIVATE_USE_CHAR: char = '\u{F0000}'; + +/// A face that maps only [`PRIVATE_USE_CHAR`] to the bundled Source Sans 3 `H` outline, for tests +/// that need a character no other font covers, with or without craft-fonts. +pub fn private_use_font() -> Option> { + remapped_source_sans(PRIVATE_USE_FAMILY, "PrivateUseSans-Regular", &[(PRIVATE_USE_CHAR, 'H')]) +} + /// The family of [`large_cmap_font`]. pub const LARGE_CMAP_FAMILY: &str = "Largecmap Sans"; diff --git a/crates/text/web-fonts.txt b/crates/text/web-fonts.txt index 7dbb8953b3..235ba98e13 100644 --- a/crates/text/web-fonts.txt +++ b/crates/text/web-fonts.txt @@ -2,6 +2,8 @@ # One face per line: when | family | style (family and style as in craft-fonts' fonts/manifest.txt). # startup = fetched before the app starts (fallbacks the first frame needs) # background = fetched after the app starts (fonts users pick by name) +# demand = fetched only when the interface language or the interface's own text needs one of +# the face's scripts (Korean, Hindi) # Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook). startup | Noto Sans Arabic | Regular startup | Noto Sans Thai | Regular @@ -36,3 +38,5 @@ background | Reem Kufi | Regular background | Aref Ruqaa | Regular background | Aref Ruqaa | Bold background | Gulzar | Regular +demand | NanumGothic | Regular +demand | Noto Sans Devanagari | Regular diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 2dbff773f9..1bfb46f93b 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -34,6 +34,18 @@ pub enum LineKind { Perforation, } +impl LineKind { + /// The angle (degrees) a line of this kind folds at: 90 for a Crease or a Perforation, -90 for + /// a Partial Cut. A positive angle folds away from the printed side; none for a Cut. + pub fn fold_angle(self) -> Option { + match self { + LineKind::Cut => None, + LineKind::Crease | LineKind::Perforation => Some(90.0), + LineKind::PartialCut => Some(-90.0), + } + } +} + /// A fold line: the path (document coordinates), its kind, and a key the issues name it by. #[derive(Clone, Debug)] pub struct FoldLine { @@ -57,10 +69,18 @@ pub struct Panel { pub area: f64, } +impl Panel { + /// A point inside the panel, or the middle of its bounds for one too thin to find one in. + pub fn point_inside(&self) -> Option { + point_in(&self.outline) + } +} + /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. +/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is +/// ([`LineKind::fold_angle`]). #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, @@ -69,6 +89,7 @@ pub struct Hinge { pub to: Point, pub keys: Vec, pub straight: bool, + pub angle: f64, } /// What can be wrong with fold lines, in the order [`blanks`] lists them. @@ -1276,7 +1297,9 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let (p0, p1) = group.iter().filter_map(|p| chord(p)).max_by(|x, y| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let ((p0, p1), longest) = + group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1308,7 +1331,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1426,7 +1449,7 @@ impl Context<'_> { /// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of /// the larger tie, and the tie goes to the one whose inside point is highest on the page, then /// leftmost. -fn base_panel(panels: &[Panel]) -> Option { +pub fn base_panel(panels: &[Panel]) -> Option { let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); if !top.is_finite() { return None; @@ -1440,5 +1463,9 @@ fn base_panel(panels: &[Panel]) -> Option { .map(|(i, _)| i) } +mod pose; +pub mod raster; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs new file mode 100644 index 0000000000..650ab54291 --- /dev/null +++ b/crates/three-d/src/fold/pose.rs @@ -0,0 +1,407 @@ +//! A blank folded into its 3D shape ([`fold`]). +//! +//! The flat blank lies at z = 0 with document x to the right and document y flipped so y points up; +//! the printed side faces +z. The base panel stays in place. The other panels are reached from it +//! through a breadth-first tree of hinges, each panel's hinges taken in the order of their ends (y, +//! then x, the first end first), so the tree does not depend on the order the lines were drawn in. A child +//! panel turns about its hinge by the hinge's angle times the fold amount; a positive angle moves it +//! toward -z, away from the printed side, whichever way the hinge was drawn. Hinges outside the tree +//! close a loop of panels: [`FoldedHinge::gap`] says how far apart their two placements end up when +//! the blank is folded all the way. + +use std::collections::{HashSet, VecDeque}; + +use vectorcraft_geom::{PathData, PathEl, Point, Shape as _}; + +use super::{Blank, base_panel, point_in}; + +/// Most points a panel's outline is flattened to; a panel with more is left out of the collision +/// test and the preview. +pub const MAX_POLYGON_POINTS: usize = 1 << 16; + +type V3 = [f64; 3]; + +fn sub(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn add(a: V3, b: V3) -> V3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} + +fn scale(a: V3, s: f64) -> V3 { + [a[0] * s, a[1] * s, a[2] * s] +} + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn length(a: V3) -> f64 { + dot(a, a).sqrt() +} + +/// A document point on the flat blank (y flipped so it points up, z = 0). +pub(super) fn flat(p: Point) -> V3 { + [p.x, -p.y, 0.0] +} + +/// Where a panel is: a rotation `m` (rows) and a translation `t`, taking a point of the flat +/// blank (see [`flat`]) to its place in 3D. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + pub m: [[f64; 3]; 3], + pub t: [f64; 3], +} + +impl Pose { + /// The flat blank's own place. + pub const IDENTITY: Pose = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] }; + + /// Where the flat point `v` goes. + pub fn apply(&self, v: [f64; 3]) -> [f64; 3] { + add(self.turn(v), self.t) + } + + /// The direction `v` turned by the rotation alone. + pub fn turn(&self, v: [f64; 3]) -> [f64; 3] { + let [a, b, c] = self.m; + [dot(a, v), dot(b, v), dot(c, v)] + } + + /// Where the document point `p` goes. + pub fn place(&self, p: Point) -> [f64; 3] { + self.apply(flat(p)) + } + + /// The direction the printed side faces. + pub fn normal(&self) -> [f64; 3] { + self.turn([0.0, 0.0, 1.0]) + } + + /// This pose followed, in the flat blank's terms, by a right-handed turn of `theta` radians + /// about the line through `at` along the unit direction `axis`: the pose of a panel hinged to + /// this one there. + fn turned_about(&self, at: V3, axis: V3, theta: f64) -> Pose { + let (s, c) = theta.sin_cos(); + let [x, y, z] = axis; + // Rodrigues' rotation matrix. + let r = [ + [c + x * x * (1.0 - c), x * y * (1.0 - c) - z * s, x * z * (1.0 - c) + y * s], + [y * x * (1.0 - c) + z * s, c + y * y * (1.0 - c), y * z * (1.0 - c) - x * s], + [z * x * (1.0 - c) - y * s, z * y * (1.0 - c) + x * s, c + z * z * (1.0 - c)], + ]; + let mut m = [[0.0; 3]; 3]; + for (i, row) in m.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = (0..3).map(|k| self.m[i][k] * r[k][j]).sum(); + } + } + // p ↦ self(r (p - at) + at) = (self.m r) p + self.m (at - r at) + self.t + let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; + Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } + } +} + +/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no +/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it +/// and the base. +#[derive(Clone, Debug)] +pub struct FoldedPanel { + pub pose: Pose, + pub parent: Option, + pub depth: usize, +} + +/// A folded hinge: its panels, its angle (degrees, before the fold amount), whether it is in the +/// fold tree and, for one that is not, how far apart its two placements end up with every hinge at +/// its full angle, whatever the fold amount (`gap`, points), and whether that is close enough to call +/// it closed. +#[derive(Clone, Debug)] +pub struct FoldedHinge { + pub a: usize, + pub b: usize, + pub angle: f64, + pub tree: bool, + pub closes: bool, + pub gap: f64, +} + +/// A blank folded at one amount. +#[derive(Clone, Debug)] +pub struct Folded { + pub base: usize, + pub panels: Vec, + /// The panels in breadth-first order from the base, the panels not joined to it last. + pub order: Vec, + pub hinges: Vec, + /// Pairs of panels (`a` < `b`) that pass through each other. + pub collisions: Vec<(usize, usize)>, +} + +/// The panel of `blank` that `p` (document coordinates) lies in. +pub fn panel_at(blank: &Blank, p: Point) -> Option { + blank.panels.iter().position(|panel| panel.outline.to_bezpath().winding(p) != 0) +} + +/// Which of `blanks` to fold, and about which of its panels: the blank and panel `at` (document +/// coordinates) lies in, or, without a point, the blank with the largest panel (the first of equals) +/// and its base panel. `None` when `at` lies in no panel, or no blank has a panel. +pub fn pick(blanks: &[Blank], at: Option) -> Option<(usize, usize)> { + match at { + Some(p) => blanks.iter().enumerate().find_map(|(i, b)| Some((i, panel_at(b, p)?))), + None => { + let largest = |b: &Blank| b.panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); + let (i, b) = + blanks.iter().enumerate().filter(|(_, b)| !b.panels.is_empty()).fold(None, |best: Option<(usize, &Blank)>, (i, b)| match best { + Some((_, kept)) if largest(kept) >= largest(b) => best, + _ => Some((i, b)), + })?; + Some((i, base_panel(&b.panels)?)) + } + } +} + +/// `blank` folded about its panel `base` (the largest when `None`) by `amount` (0, flat, to 1, every +/// hinge at its angle). `tolerance` (points) is how far apart a closing hinge's placements may end +/// up and still close (or 0.5% of its length, when that is more), and how far apart two panels in +/// one plane may lie and still be stacked rather than crossing. `None` when the blank has no +/// panels, `base` is not one of them, or `amount` is not from 0 to 1. +pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> Option { + let base = match base { + Some(b) => b, + None => base_panel(&blank.panels)?, + }; + if base >= blank.panels.len() || !(0.0..=1.0).contains(&amount) { + return None; + } + let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.01 }; + let n = blank.panels.len(); + // Each panel's hinges, by the place they start (y, then x), then by the other panel. + let mut by_panel: Vec> = vec![vec![]; n]; + for (i, h) in blank.hinges.iter().enumerate() { + for p in [h.a, h.b] { + if let Some(list) = by_panel.get_mut(p) { + list.push(i); + } + } + } + // A hinge's ends, the one first by (y, x) first. + let ends = |i: &usize| { + blank.hinges.get(*i).map_or([f64::INFINITY; 4], |h| { + let (s, e) = if (h.from.y, h.from.x) <= (h.to.y, h.to.x) { (h.from, h.to) } else { (h.to, h.from) }; + [s.y, s.x, e.y, e.x] + }) + }; + for list in &mut by_panel { + list.sort_by(|a, b| { + let (ka, kb) = (ends(a), ends(b)); + ka.iter().zip(&kb).fold(std::cmp::Ordering::Equal, |o, (x, y)| o.then(x.total_cmp(y))).then(a.cmp(b)) + }); + } + let centers: Vec> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); + let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // Closing hinges are measured with every hinge at its full angle, so a blank that closes when + // folded is not reported open part of the way there. + let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let measured = full.as_deref().unwrap_or(&panels); + let hinges = blank + .hinges + .iter() + .zip(&tree) + .map(|(h, &tree)| { + let (pa, pb) = (measured.get(h.a).map(|p| p.pose), measured.get(h.b).map(|p| p.pose)); + let gap = match (pa, pb) { + (Some(pa), Some(pb)) if !tree => [h.from, h.to].iter().map(|&e| length(sub(pa.place(e), pb.place(e)))).fold(0.0, f64::max), + _ => 0.0, + }; + let closes = tree || gap <= tolerance.max(0.005 * h.from.distance(h.to)); + FoldedHinge { a: h.a, b: h.b, angle: h.angle, tree, closes, gap } + }) + .collect(); + let collisions = collisions(blank, &panels, tolerance); + Some(Folded { base, panels, order, hinges, collisions }) +} + +/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not +/// joined to the base last). +fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: usize, amount: f64) -> (Vec, Vec, Vec) { + let n = blank.panels.len(); + let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut reached = vec![false; n]; + let mut tree = vec![false; blank.hinges.len()]; + let mut order = Vec::with_capacity(n); + let mut queue = VecDeque::from([base]); + if let Some(r) = reached.get_mut(base) { + *r = true; + } + while let Some(p) = queue.pop_front() { + order.push(p); + let Some(parent) = panels.get(p).cloned() else { continue }; + for &hi in by_panel.get(p).map(Vec::as_slice).unwrap_or_default() { + let Some(h) = blank.hinges.get(hi) else { continue }; + let child = if h.a == p { h.b } else { h.a }; + if reached.get(child) != Some(&false) { + continue; + } + let (mut from, mut to) = (flat(h.from), flat(h.to)); + let len = length(sub(to, from)); + if !(len.is_finite() && len > 0.0) { + continue; + } + // The parent on the left of the hinge's direction, the child on its right. The side is + // read next to the hinge, so a parent with a notch or an arm past the hinge's line still + // turns the child the right way; the panel's inside point is the fallback. + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + Some(left) => left, + None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), + }; + if !left { + std::mem::swap(&mut from, &mut to); + } + let axis = scale(sub(to, from), 1.0 / len); + let theta = (h.angle * amount).to_radians(); + if !theta.is_finite() { + continue; + } + if let Some(slot) = panels.get_mut(child) { + *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + } + if let Some(r) = reached.get_mut(child) { + *r = true; + } + if let Some(t) = tree.get_mut(hi) { + *t = true; + } + queue.push_back(child); + } + } + order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); + (panels, tree, order) +} + +/// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) +/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and +/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset +/// tells them apart. The nearest offset is tried first. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option { + let bp = outline.to_bezpath(); + let mid = scale(add(from, to), 0.5); + let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; + let doc = |v: V3| Point::new(v[0], -v[1]); + let mut offsets = [1e-3, 0.25, len * 0.01]; + offsets.sort_by(f64::total_cmp); + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); + (l != r).then_some(l) + }) +} + +/// The rings of `path` flattened to `tolerance`, in document coordinates; `None` past +/// [`MAX_POLYGON_POINTS`] points. +pub fn polygon(path: &PathData, tolerance: f64) -> Option>> { + let mut rings: Vec> = vec![]; + let mut count = 0usize; + let mut fits = true; + vectorcraft_geom::flatten(path.to_bezpath(), tolerance, |el| { + if !fits { + return; + } + match el { + PathEl::MoveTo(p) => rings.push(vec![p]), + PathEl::LineTo(p) => match rings.last_mut() { + Some(r) => r.push(p), + None => rings.push(vec![p]), + }, + _ => return, + } + count += 1; + fits = count <= MAX_POLYGON_POINTS; + }); + rings.retain(|r| r.len() >= 3); + (fits && rings.iter().flatten().all(|p| p.is_finite())).then_some(rings) +} + +/// A panel placed in 3D: its rings, the plane it lies in (unit normal and offset) and its bounds. +struct Placed { + rings: Vec>, + normal: V3, + offset: f64, + lo: V3, + hi: V3, +} + +/// The pairs of `panels` that pass through each other. Two panels hinged to each other are not +/// tested, nor two in parallel planes (stacked in one plane, or apart). +fn collisions(blank: &Blank, panels: &[FoldedPanel], tolerance: f64) -> Vec<(usize, usize)> { + let placed: Vec> = blank + .panels + .iter() + .zip(panels) + .map(|(panel, f)| { + let rings: Vec> = + polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| f.pose.place(p)).collect()).collect(); + let all = rings.iter().flatten(); + let lo = all.clone().fold([f64::INFINITY; 3], |a, p| [a[0].min(p[0]), a[1].min(p[1]), a[2].min(p[2])]); + let hi = all.fold([f64::NEG_INFINITY; 3], |a, p| [a[0].max(p[0]), a[1].max(p[1]), a[2].max(p[2])]); + let normal = f.pose.normal(); + let offset = dot(normal, f.pose.t); + Some(Placed { rings, normal, offset, lo, hi }) + }) + .collect(); + let hinged: HashSet<(usize, usize)> = blank.hinges.iter().map(|h| (h.a.min(h.b), h.a.max(h.b))).collect(); + let mut out = vec![]; + for (i, a) in placed.iter().enumerate() { + let Some(a) = a else { continue }; + for (j, b) in placed.iter().enumerate().skip(i + 1) { + let Some(b) = b else { continue }; + if hinged.contains(&(i, j)) || (0..3).any(|k| a.hi[k] + tolerance < b.lo[k] || b.hi[k] + tolerance < a.lo[k]) { + continue; + } + let line = cross(a.normal, b.normal); + let along = length(line); + if along.is_nan() || along <= 1e-9 { + continue; + } + let u = scale(line, 1.0 / along); + let on_a = crossings(&a.rings, b.normal, b.offset, u, tolerance); + let on_b = crossings(&b.rings, a.normal, a.offset, u, tolerance); + if on_a.iter().any(|x| on_b.iter().any(|y| x.1.min(y.1) - x.0.max(y.0) > tolerance)) { + out.push((i, j)); + } + } + } + out +} + +/// Where `rings` cross the plane `normal · p = offset`: the spans of the line along `u` that lie +/// inside them, by their place along `u`. A panel with no point more than `tolerance` to one side +/// of the plane only touches it, and crosses it nowhere; otherwise points within `tolerance` of it +/// count as on its positive side. +fn crossings(rings: &[Vec], normal: V3, offset: f64, u: V3, tolerance: f64) -> Vec<(f64, f64)> { + let side = |p: V3| dot(normal, p) - offset; + let sides = rings.iter().flatten().map(|&p| side(p)); + let (above, below) = sides.fold((false, false), |(a, b), s| (a || s > tolerance, b || s < -tolerance)); + if !(above && below) { + return vec![]; + } + let mut at = vec![]; + for ring in rings { + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (sp, sq) = (side(p), side(q)); + if (sp >= -tolerance) != (sq >= -tolerance) { + let t = (sp / (sp - sq)).clamp(0.0, 1.0); + at.push(dot(u, add(p, scale(sub(q, p), t)))); + } + } + } + at.retain(|x| x.is_finite()); + at.sort_by(f64::total_cmp); + at.as_chunks::<2>().0.iter().map(|&[a, b]| (a, b)).collect() +} diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs new file mode 100644 index 0000000000..9cccbaf6d9 --- /dev/null +++ b/crates/three-d/src/fold/raster.rs @@ -0,0 +1,495 @@ +//! Draws a [`Folded`] blank as pixels: each panel's outline is projected through the view and filled +//! by scanline, with a depth buffer, and each pixel takes its color from a raster of the flat print +//! (the printed side) or from the inside color (the back), shaded by the panel's slope to a fixed +//! light. The inverse of the panel's projective map gives the flat point under every pixel, so the +//! print is drawn without seams under perspective. With perspective, each panel is cut at a near +//! plane in front of the eye before it is projected. + +use vectorcraft_geom::{Point, Rect}; + +use super::pose::{Folded, polygon}; +use super::{Blank, Panel}; + +/// Most pixels a side of the view or of the print raster may have. +pub const MAX_SIDE: u32 = 4096; +/// Most pixels the view may have in all (2,048 × 1,024; 32 MiB of buffers). +pub const MAX_PIXELS: u32 = 1 << 21; +/// The share of the eye's distance a panel is cut at in front of the eye. +const NEAREST: f64 = 1e-3; +/// How far apart (points of view depth) two panels may be and still tie. +const TIE: f64 = 1e-4; +/// The light's direction: above, to the left of and toward the viewer. +const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; + +type V3 = [f64; 3]; + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// The view: its size in pixels, its turn (degrees: `rotate_x` tips the top toward the viewer, +/// `rotate_y` turns the right side toward the viewer), its scale (pixels per point at the center's +/// depth), how far it is moved (pixels), its perspective (the field of view in degrees; 0 for none) +/// and the 3D point at its middle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub width: u32, + pub height: u32, + pub rotate_x: f64, + pub rotate_y: f64, + pub scale: f64, + pub pan: [f64; 2], + pub perspective: f64, + pub center: [f64; 3], +} + +impl Camera { + /// The turn from 3D to the view's own axes (x right, y up, z toward the viewer), as rows. + fn rotation(&self) -> [[f64; 3]; 3] { + let (sx, cx) = self.rotate_x.to_radians().sin_cos(); + let (sy, cy) = (-self.rotate_y).to_radians().sin_cos(); + // Rx · Ry + [[cy, 0.0, sy], [sx * sy, cx, -sx * cy], [-cx * sy, sx, cx * cy]] + } + + /// The point `p` in the view's own axes, its middle at the origin. + pub fn to_view(&self, p: V3) -> V3 { + let r = self.rotation(); + let d = [p[0] - self.center[0], p[1] - self.center[1], p[2] - self.center[2]]; + [dot(r[0], d), dot(r[1], d), dot(r[2], d)] + } + + /// The distance (points) from the eye to the view's middle and the focal length (pixels) under + /// perspective; `None` without it. + fn eye(&self) -> Option<(f64, f64)> { + if self.perspective <= 0.0 || self.perspective >= 180.0 { + return None; + } + let half = f64::from(self.width.min(self.height)) / 2.0; + let focal = half / (self.perspective.to_radians() / 2.0).tan(); + let eye = focal / self.scale; + (focal.is_finite() && eye.is_finite() && eye > 0.0).then_some((eye, focal)) + } + + fn usable(&self) -> bool { + let finite = + [self.rotate_x, self.rotate_y, self.scale, self.pan[0], self.pan[1], self.perspective].iter().chain(&self.center).all(|v| v.is_finite()); + let pixels = u64::from(self.width) * u64::from(self.height); + finite && self.scale > 0.0 && (1..=MAX_SIDE).contains(&self.width) && (1..=MAX_SIDE).contains(&self.height) && pixels <= u64::from(MAX_PIXELS) + } +} + +/// One level of the print raster: premultiplied RGBA, 4 bytes a pixel. +#[derive(Clone, Debug)] +pub struct Level { + pub width: u32, + pub height: u32, + pub pixels: Vec, +} + +impl Level { + /// The color at pixel `(x, y)`, clamped to the edges. + fn at(&self, x: i64, y: i64) -> [f32; 4] { + let x = x.clamp(0, i64::from(self.width) - 1); + let y = y.clamp(0, i64::from(self.height) - 1); + let i = usize::try_from((y * i64::from(self.width) + x) * 4).unwrap_or(usize::MAX); + match self.pixels.get(i..i.saturating_add(4)) { + Some(&[r, g, b, a]) => [f32::from(r), f32::from(g), f32::from(b), f32::from(a)], + _ => [0.0; 4], + } + } + + /// The color at `(x, y)` (pixels), between the four nearest pixels. + fn sample(&self, x: f64, y: f64) -> [f32; 4] { + let (fx, fy) = (x - 0.5, y - 0.5); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32); + let (x0, y0) = (x0 as i64, y0 as i64); + let (a, b, c, d) = (self.at(x0, y0), self.at(x0 + 1, y0), self.at(x0, y0 + 1), self.at(x0 + 1, y0 + 1)); + let mut out = [0.0; 4]; + for (k, o) in out.iter_mut().enumerate() { + let top = a[k] + (b[k] - a[k]) * tx; + let bottom = c[k] + (d[k] - c[k]) * tx; + *o = top + (bottom - top) * ty; + } + out + } + + /// This level at half its size, rounded up, each pixel the mean of the pixels it covers weighted + /// by the area of the full print they cover. A pixel of this level is `step` pixels of the full + /// print (`base` pixels across and down) on a side, and fewer in the last column and row when + /// `base` is not a multiple of `step`. + fn half(&self, base: (u32, u32), step: u32) -> Option { + let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2)); + if (w, h) == (self.width, self.height) { + return None; + } + // The pixels of the full print that column or row `i` of this level covers, or 0 past it. + let covers = |i: u32, side: u32| u64::from(side).saturating_sub(u64::from(i) * u64::from(step)).min(u64::from(step)) as f32; + let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..h { + for x in 0..w { + let mut sum = [0.0f32; 4]; + let mut area = 0.0; + for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] { + if sx >= self.width || sy >= self.height { + continue; + } + let a = covers(sx, base.0) * covers(sy, base.1); + let p = self.at(i64::from(sx), i64::from(sy)); + for (s, c) in sum.iter_mut().zip(p) { + *s += c * a; + } + area += a; + } + for s in sum { + pixels.push(if area > 0.0 { (s / area).round() as u8 } else { 0 }); + } + } + } + Some(Level { width: w, height: h, pixels }) + } +} + +/// The flat print: the document rect it covers and its raster at full size and halved again and +/// again down to one pixel. +#[derive(Clone, Debug)] +pub struct Print { + pub region: Rect, + pub levels: Vec, +} + +impl Print { + /// The print of `region` from `pixels` (premultiplied RGBA, `width` × `height`); `None` when + /// the sizes do not agree, a side is 0 or more than [`MAX_SIDE`], or the region is empty. + pub fn new(region: Rect, width: u32, height: u32, pixels: Vec) -> Option { + let fits = (1..=MAX_SIDE).contains(&width) && (1..=MAX_SIDE).contains(&height); + let empty = !(region.width() > 0.0 && region.height() > 0.0 && region.is_finite()); + if !fits || empty || pixels.len() != width as usize * height as usize * 4 { + return None; + } + let mut levels = vec![Level { width, height, pixels }]; + let mut step = 1; + while let Some(next) = levels.last().and_then(|l| l.half((width, height), step)) { + levels.push(next); + step *= 2; + } + Some(Print { region, levels }) + } + + /// The print's color (premultiplied, 0 to 255) at document point `p`, from the level whose + /// pixels are closest to `footprint` points across; transparent outside the region. + fn sample(&self, p: Point, footprint: f64) -> [f32; 4] { + let Some(base) = self.levels.first() else { return [0.0; 4] }; + if !self.region.contains(p) { + return [0.0; 4]; + } + let per_point = f64::from(base.width) / self.region.width(); + let level = if footprint.is_finite() && footprint > 0.0 { (footprint * per_point).log2().floor().max(0.0) as usize } else { 0 }; + let level = level.min(self.levels.len() - 1); + let Some(l) = self.levels.get(level) else { return [0.0; 4] }; + // Each level halves the one before it, so a pixel of level n covers 2ⁿ of the first's. + let shrink = f64::from(1u32 << level); + let sx = f64::from(base.width) / self.region.width() / shrink; + let sy = f64::from(base.height) / self.region.height() / shrink; + l.sample((p.x - self.region.x0) * sx, (p.y - self.region.y0) * sy) + } +} + +/// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of +/// its printed side where the print has no art (straight RGBA; the board is opaque, so their alpha +/// is not used), and the view. +pub struct Scene<'a> { + pub blank: &'a Blank, + pub folded: &'a Folded, + pub print: Option<&'a Print>, + pub inside: [u8; 4], + pub outside: [u8; 4], + pub camera: Camera, +} + +/// A drawn view: premultiplied RGBA, 4 bytes a pixel, transparent where no panel is; and for each +/// pixel the panel drawn there plus 1 (0 for none). +#[derive(Clone, Debug)] +pub struct Image { + pub width: u32, + pub height: u32, + pub pixels: Vec, + pub panels: Vec, +} + +impl Image { + /// The panel drawn at pixel `(x, y)`. + pub fn panel_at(&self, x: u32, y: u32) -> Option { + if x >= self.width || y >= self.height { + return None; + } + let i = y as usize * self.width as usize + x as usize; + self.panels.get(i).and_then(|&p| usize::from(p).checked_sub(1)) + } +} + +/// The 3D bounds of `blank`'s panels folded as `folded` places them (low and high corners). +pub fn bounds(blank: &Blank, folded: &Folded) -> Option<(V3, V3)> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for (panel, f) in blank.panels.iter().zip(&folded.panels) { + let Some(b) = panel.outline.bounds() else { continue }; + for c in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)] { + let p = f.pose.place(c); + for k in 0..3 { + lo[k] = lo[k].min(p[k]); + hi[k] = hi[k].max(p[k]); + } + } + } + lo.iter().chain(&hi).all(|v| v.is_finite()).then_some((lo, hi)) +} + +/// A panel ready to fill: its projective map from the flat blank to the view and back, its depth +/// plane in view terms, and its color factors. +struct Mapped { + /// Flat (u, v, 1) → (x w, y w, w) in pixels, as rows. + forward: [[f64; 3]; 3], + /// The inverse of `forward`. + inverse: [[f64; 3]; 3], + /// View depth at flat (u, v): u a + v b + c. + depth: [f64; 3], + printed: bool, + shade: f32, +} + +fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 { + [dot(m[0], v), dot(m[1], v), dot(m[2], v)] +} + +fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { + let [[a, b, c], [d, e, f], [g, h, i]] = *m; + let co = [e * i - f * h, f * g - d * i, d * h - e * g]; + let det = a * co[0] + b * co[1] + c * co[2]; + if !(det.is_finite() && det.abs() > 1e-300) { + return None; + } + let inv = [ + [co[0] / det, (c * h - b * i) / det, (b * f - c * e) / det], + [co[1] / det, (a * i - c * g) / det, (c * d - a * f) / det], + [co[2] / det, (b * g - a * h) / det, (a * e - b * d) / det], + ]; + inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) +} + +fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option { + let r = camera.rotation(); + let turn = |v: V3| mul(&r, f.pose.turn(v)); + let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); + let o = camera.to_view(f.pose.t); + let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); + let normal = turn([0.0, 0.0, 1.0]); + let (w, k, printed) = match camera.eye() { + Some((eye, focal)) => ([-a[2], -b[2], eye - o[2]], focal, dot(normal, [-o[0], -o[1], eye - o[2]]) > 0.0), + None => ([0.0, 0.0, 1.0], camera.scale, normal[2] > 0.0), + }; + let x = [cx * w[0] + k * a[0], cx * w[1] + k * b[0], cx * w[2] + k * o[0]]; + let y = [cy * w[0] - k * a[1], cy * w[1] - k * b[1], cy * w[2] - k * o[1]]; + let forward = [x, y, w]; + let inverse = invert(&forward)?; + let facing = if printed { normal } else { [-normal[0], -normal[1], -normal[2]] }; + let shade = (0.6 + 0.4 * dot(facing, LIGHT).max(0.0)) as f32; + Some(Mapped { forward, inverse, depth: [a[2], b[2], o[2]], printed, shade }) +} + +/// `ring` (flat points) cut to the side of the plane `w · (u, v, 1) ≥ near`. +fn clip(ring: &[[f64; 2]], w: V3, near: f64) -> Vec<[f64; 2]> { + let at = |p: [f64; 2]| dot(w, [p[0], p[1], 1.0]) - near; + let mut out = Vec::with_capacity(ring.len() + 4); + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (dp, dq) = (at(p), at(q)); + if dp >= 0.0 { + out.push(p); + } + if (dp >= 0.0) != (dq >= 0.0) { + let t = dp / (dp - dq); + out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]); + } + } + out +} + +/// The buffers [`render`] fills. +struct Target { + width: usize, + height: usize, + color: Vec, + depth: Vec, + rank: Vec, + panel: Vec, +} + +/// One panel's fill: its map, rank (for ties), panel number and colors. +struct Fill<'a> { + mapped: &'a Mapped, + rank: u16, + panel: u16, + print: Option<&'a Print>, + inside: [f32; 4], + outside: [f32; 4], +} + +impl Fill<'_> { + /// The document point under pixel center `(x, y)`, or `None` behind the eye. + fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { + let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); + (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) + } + + /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. + fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { + let base = if self.mapped.printed { + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let under = 1.0 - p[3] / 255.0; + [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] + } else { + self.inside + }; + let s = self.mapped.shade; + [base[0] * s, base[1] * s, base[2] * s, base[3]] + } + + /// Fill the span of row `row` from `x0` to `x1` (pixel coordinates) into `target`. + fn span(&self, target: &mut Target, row: usize, x0: f64, x1: f64) { + let first = (x0 - 0.5).ceil().max(0.0); + let last = ((x1 - 0.5).ceil() - 1.0).min(target.width as f64 - 1.0); + if first > last { + return; + } + let y = row as f64 + 0.5; + for col in first as usize..=last as usize { + let x = col as f64 + 0.5; + let Some((u, v)) = self.flat_at(x, y) else { continue }; + let [a, b, c] = self.mapped.depth; + let z = u * a + v * b + c; + let i = row * target.width + col; + let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; + let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + if !wins { + continue; + } + // The print's footprint is the longer of a pixel's two sides in flat terms. + let across = |dx: f64, dy: f64| self.flat_at(x + dx, y + dy).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + let footprint = across(1.0, 0.0).max(across(0.0, 1.0)); + let color = self.color(u, v, footprint); + if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) { + for (o, c) in px.iter_mut().zip(color) { + *o = c.round().clamp(0.0, 255.0) as u8; + } + } + if let Some(d) = target.depth.get_mut(i) { + *d = z; + } + if let Some(r) = target.rank.get_mut(i) { + *r = self.rank; + } + if let Some(p) = target.panel.get_mut(i) { + *p = self.panel; + } + } + } + + /// Fill the projected `rings` (pixel coordinates), even-odd, into `target`. + fn rings(&self, target: &mut Target, rings: &[Vec<[f64; 2]>]) { + let ys = rings.iter().flatten().map(|p| p[1]); + let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); + if !(lo.is_finite() && hi.is_finite()) { + return; + } + let first = (lo - 0.5).ceil().max(0.0); + let last = (hi - 0.5).floor().min(target.height as f64 - 1.0); + if first > last { + return; + } + let mut xs = vec![]; + for row in first as usize..=last as usize { + let y = row as f64 + 0.5; + xs.clear(); + for ring in rings { + for (k, p) in ring.iter().enumerate() { + let Some(q) = ring.get((k + 1) % ring.len()) else { continue }; + if (p[1] <= y) != (q[1] <= y) { + xs.push(p[0] + (y - p[1]) * (q[0] - p[0]) / (q[1] - p[1])); + } + } + } + xs.retain(|x| x.is_finite()); + xs.sort_by(f64::total_cmp); + for &[a, b] in xs.as_chunks::<2>().0 { + self.span(target, row, a, b); + } + } + } +} + +/// The board color `c` as drawn: its RGB, opaque. +fn opaque(c: [u8; 4]) -> [f32; 4] { + [f32::from(c[0]), f32::from(c[1]), f32::from(c[2]), 255.0] +} + +/// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a +/// point. +fn flat_rings(panel: &Panel, scale: f64) -> Option>> { + let b = panel.outline.bounds()?; + let tolerance = (0.25 / scale).max((b.width() + b.height()) * 1e-5).max(1e-6); + Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) +} + +/// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more +/// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than +/// [`super::MAX_POLYGON_POINTS`] points, are left out. +pub fn render(scene: &Scene) -> Option { + let camera = scene.camera; + if !camera.usable() { + return None; + } + let (width, height) = (camera.width as usize, camera.height as usize); + let pixels = width * height; + let mut target = + Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; + let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); + let near = camera.eye().map(|(eye, _)| eye * NEAREST); + for (rank, &pi) in scene.folded.order.iter().enumerate() { + let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; + let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let projected: Vec> = rings + .iter() + .map(|r| match near { + Some(near) => clip(r, mapped.forward[2], near), + None => r.clone(), + }) + .filter(|r| r.len() >= 3) + .map(|r| { + r.into_iter() + .filter_map(|[u, v]| { + let [x, y, w] = mul(&mapped.forward, [u, v, 1.0]); + let p = [x / w, y / w]; + (w > 0.0 && p[0].is_finite() && p[1].is_finite()).then_some(p) + }) + .collect::>() + }) + .filter(|r| r.len() >= 3) + .collect(); + let fill = Fill { + mapped: &mapped, + rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), + print: scene.print, + inside, + outside, + }; + fill.rings(&mut target, &projected); + } + Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs new file mode 100644 index 0000000000..8639615a53 --- /dev/null +++ b/crates/three-d/src/fold/raster/tests.rs @@ -0,0 +1,257 @@ +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::*; + +fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { + SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) +} + +fn panel(subpaths: Vec) -> Panel { + Panel { outline: PathData::new(subpaths), area: 0.0 } +} + +/// A blank of `panels` and a fold that places each at `poses`, in the order given. +fn scene_of(panels: Vec, poses: Vec) -> (Blank, Folded) { + let n = panels.len(); + let folded = Folded { + base: 0, + panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + order: (0..n).collect(), + hinges: vec![], + collisions: vec![], + }; + (Blank { panels, hinges: vec![], holes: vec![] }, folded) +} + +/// Facing the printed side, 100 × 100 pixels, one pixel a point, the flat square 0..100 filling it. +fn front() -> Camera { + Camera { width: 100, height: 100, rotate_x: 0.0, rotate_y: 0.0, scale: 1.0, pan: [0.0; 2], perspective: 0.0, center: [50.0, -50.0, 0.0] } +} + +fn moved(z: f64) -> Pose { + Pose { t: [0.0, 0.0, z], ..Pose::IDENTITY } +} + +fn pixel(img: &Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// A 2 × 2 print of the square 0..100: red, green on top; blue, white below. +fn quads() -> Print { + let px = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]]; + Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 2, 2, px.concat()).expect("a print") +} + +const WHITE: [u8; 4] = [255, 255, 255, 255]; + +#[test] +fn a_flat_panel_takes_the_print_s_color_under_each_pixel() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + assert_eq!(pixel(&img, 5, 5), [lit(255.0), 0, 0, 255], "top left is red"); + assert_eq!(pixel(&img, 94, 5), [0, lit(255.0), 0, 255], "top right is green"); + assert_eq!(pixel(&img, 5, 94), [0, 0, lit(255.0), 255], "bottom left is blue"); + assert_eq!(img.panel_at(50, 50), Some(0)); + // Where the print has no art, the board's printed side shows. + let empty = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 1, 1, vec![0; 4]).expect("a print"); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&empty), inside: [0, 0, 0, 255], outside: [200, 100, 50, 255], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]); +} + +#[test] +fn the_board_is_opaque_whatever_the_alpha_of_its_colors() { + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for a in [0, 128] { + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: [200, 100, 50, a], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255], "outside alpha {a}"); + } + // A transparent inside color draws opaque too, on the nearer of two panels seen from the back. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(5.0)]); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 200, 0, 0], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn a_print_squeezed_only_up_and_down_on_screen_samples_a_halved_level() { + // 64 × 64, rows alternating black and white: halved, they average to gray. + let mut px = vec![]; + for y in 0..64 { + for _ in 0..64 { + px.extend(if y % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // Tipped 80°: about 5.8 points a pixel up and down, 1 across. + let camera = Camera { rotate_x: 80.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let reds: Vec = (0..img.height) + .flat_map(|y| (0..img.width).map(move |x| (x, y))) + .filter(|&(x, y)| img.panel_at(x, y).is_some()) + .map(|(x, y)| pixel(&img, x, y)[0]) + .collect(); + assert!(!reds.is_empty()); + let (lo, hi) = (reds.iter().min().copied().unwrap_or(0), reds.iter().max().copied().unwrap_or(0)); + assert!(hi - lo <= 2, "an even gray, not black and white rows: {lo} to {hi}"); +} + +#[test] +fn the_back_of_a_panel_shows_the_inside_color() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 200, 0, 255], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let draw = |z: f64| { + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(z)]); + render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn") + }; + assert_eq!(draw(5.0).panel_at(50, 50), Some(1), "panel 1 is in front"); + assert_eq!(draw(-5.0).panel_at(50, 50), Some(0), "panel 1 is behind"); + assert_eq!(draw(0.0).panel_at(50, 50), Some(1), "a tie goes to the panel later in the order"); + // Panels that cross: each shows where it is nearer. + let tilted = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 1.0]], t: [0.0, 0.0, -25.0] }; + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, tilted]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(20, 50), Some(0), "the tilted panel is behind on the left"); + assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); +} + +#[test] +fn a_hole_in_a_panel_is_left_empty() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), None); + assert_eq!(pixel(&img, 50, 50), [0; 4]); + assert_eq!(img.panel_at(10, 50), Some(0)); +} + +#[test] +fn a_panel_past_the_eye_at_a_wide_perspective_is_cut_at_the_near_plane() { + // A long panel standing out of the page toward the viewer, through the eye. + let toward = Pose { m: [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], t: [0.0, -50.0, 0.0] }; + let (b, f) = scene_of(vec![panel(vec![square(0.0, -1000.0, 100.0, 1000.0)])], vec![toward]); + for perspective in [1.0, 60.0, 160.0, 179.0] { + let camera = Camera { perspective, scale: 8.0, rotate_x: 30.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let drawn = img.panels.iter().filter(|&&p| p != 0).count(); + assert!(drawn > 0, "{perspective}°: some of it shows"); + assert_eq!(img.pixels.len(), 100 * 100 * 4); + } +} + +#[test] +fn unusable_views_and_prints_are_refused() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for camera in [ + Camera { width: 0, ..front() }, + Camera { height: MAX_SIDE + 1, ..front() }, + Camera { width: MAX_SIDE, height: MAX_PIXELS / MAX_SIDE + 1, ..front() }, + Camera { scale: 0.0, ..front() }, + Camera { rotate_x: f64::NAN, ..front() }, + Camera { center: [f64::INFINITY, 0.0, 0.0], ..front() }, + ] { + assert!(render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera }).is_none(), "{camera:?}"); + } + let region = Rect::new(0.0, 0.0, 10.0, 10.0); + assert!(Print::new(region, 2, 2, vec![0; 15]).is_none(), "too few bytes"); + assert!(Print::new(region, 0, 2, vec![]).is_none()); + assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none()); + assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region"); + let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print"); + assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::>(), vec![(8, 4), (4, 2), (2, 1), (1, 1)]); +} + +#[test] +fn halving_an_odd_sized_print_keeps_its_last_row_and_column() { + // 3 × 3, transparent but for an opaque white last column and last row. + let mut px = vec![0u8; 3 * 3 * 4]; + for i in [2, 5, 6, 7, 8] { + px[i * 4..i * 4 + 4].copy_from_slice(&[255; 4]); + } + let p = Print::new(Rect::new(0.0, 0.0, 30.0, 30.0), 3, 3, px).expect("a print"); + let half = &p.levels[1]; + assert_eq!((half.width, half.height), (2, 2)); + // The bottom right pixel of the half level covers only the corner pixel. + assert_eq!(&half.pixels[12..16], &[255; 4]); + assert_eq!(&half.pixels[0..4], &[0; 4], "the top left covers four transparent pixels"); +} + +#[test] +fn a_print_far_smaller_on_screen_samples_a_halved_level() { + // Columns alternate black and white: halved, they average to gray. + let mut px = vec![]; + for _ in 0..4 { + for x in 0..4 { + px.extend(if x % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 4, 4, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 2 pixels: 2 print pixels a view pixel. + let camera = Camera { width: 2, height: 2, scale: 0.02, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 0); + assert!((80..=150).contains(&r), "gray, not a black or white column: {r}"); +} + +#[test] +fn a_print_sixteen_times_smaller_on_screen_samples_a_level_halved_four_times() { + // 64 × 64, columns in bands of 4 alternating black and white: halved twice, they still alternate; + // halved four times, they average to gray. + let mut px = vec![]; + for _ in 0..64 { + for x in 0..64 { + px.extend(if (x / 4) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + assert_eq!(print.levels.len(), 7, "64 down to 1"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 3 pixels: about 21 print pixels a view pixel. + let camera = Camera { width: 3, height: 3, scale: 0.03, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 1); + assert!((90..=140).contains(&r), "gray, not a black or white band: {r}"); +} + +#[test] +fn a_halved_level_weighs_an_odd_last_column_by_the_area_it_covers() { + // 9 × 9, black but for a white last column: a ninth of the print, so the one-pixel level is + // a ninth white (255 / 9 is about 28), not half. + let mut px = vec![]; + for _ in 0..9 { + for x in 0..9 { + px.extend(if x == 8 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 9, 9, px).expect("a print"); + assert_eq!(print.levels.iter().map(|l| (l.width, l.height)).collect::>(), vec![(9, 9), (5, 5), (3, 3), (2, 2), (1, 1)]); + assert_eq!(print.levels.last().map(|l| l.pixels.clone()), Some(vec![28, 28, 28, 255])); +} + +#[test] +fn the_bounds_take_in_every_folded_panel() { + let (b, f) = + scene_of(vec![panel(vec![square(0.0, 0.0, 10.0, 10.0)]), panel(vec![square(0.0, 0.0, 10.0, 10.0)])], vec![Pose::IDENTITY, moved(-7.0)]); + let (lo, hi) = bounds(&b, &f).expect("bounds"); + assert_eq!((lo, hi), ([0.0, -10.0, -7.0], [10.0, 0.0, 0.0])); +} diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index ef014300c0..8031a0b2a1 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -913,4 +913,323 @@ proptest! { sorted.sort_by_key(|i| i.code); prop_assert_eq!(sorted, issues); } + + /// Random fold lines fold at any amount without a panic, every pose finite and every panel + /// keeping its shape. + #[test] + fn random_blanks_fold_to_finite_poses( + segs in proptest::collection::vec((1u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..8), + amount in 0.0f64..=1.0, + ) { + let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation]; + let mut lines: Vec = segs + .iter() + .enumerate() + .map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64)) + .collect(); + lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99)); + let (blanks, _) = blanks(&lines, TOL); + for b in &blanks { + let Some(f) = fold(b, None, amount, TOL) else { continue }; + prop_assert_eq!(f.panels.len(), b.panels.len()); + prop_assert_eq!(f.order.len(), b.panels.len()); + for p in &f.panels { + prop_assert!(p.pose.m.iter().flatten().chain(&p.pose.t).all(|v| v.is_finite())); + let n = p.pose.normal(); + prop_assert!((n[0] * n[0] + n[1] * n[1] + n[2] * n[2] - 1.0).abs() < 1e-9); + } + } + } +} + +/// The 3D corners of panel `i` of `b` folded as `f` places them. +fn corners(b: &Blank, f: &Folded, i: usize) -> Vec<[f64; 3]> { + let rings = polygon(&b.panels[i].outline, 0.01).expect("a polygon"); + rings.into_iter().flatten().map(|p| f.panels[i].pose.place(p)).collect() +} + +fn flat_center(b: &Blank, i: usize) -> [f64; 3] { + let c = point_in(&b.panels[i].outline).expect("a point inside"); + [c.x, -c.y, 0.0] +} + +#[test] +fn a_slotted_box_folds_every_panel_onto_a_face_of_the_box_with_the_print_outside() { + let (b, issues) = check(¬ched_box()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + // The base panel is the leftmost of the two largest body panels: x 20 to 120, y 30 to 110. + let base = &b.panels[f.base]; + assert_eq!(base.outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((20.0, 30.0))); + // The box: the base panel's face (z = 0), 60 deep (the narrow body panels' width). + let (lo, hi) = ([20.0, -110.0, -60.0], [120.0, -30.0, 0.0]); + let middle = [70.0, -70.0, -30.0]; + for i in 0..b.panels.len() { + let points = corners(b, &f, i); + let face = (0..3).find_map(|k| [lo[k], hi[k]].into_iter().find(|&at| points.iter().all(|p| (p[k] - at).abs() < 1e-6)).map(|at| (k, at))); + let (k, at) = face.unwrap_or_else(|| panic!("panel {i} lies on no face of the box: {points:?}")); + for p in &points { + for j in 0..3 { + assert!(p[j] > lo[j] - 1e-6 && p[j] < hi[j] + 1e-6, "panel {i} reaches out of the box: {p:?}"); + } + } + // The printed side faces out of the box. + let n = f.panels[i].pose.normal(); + assert!((n[k].abs() - 1.0).abs() < 1e-9, "panel {i} is square to its face: {n:?}"); + assert!(n[k] * (at - middle[k]) > 0.0, "panel {i}'s print faces out: {n:?}"); + } + assert!(f.hinges.iter().all(|h| h.tree && h.closes && (h.angle - 90.0).abs() < 1e-12), "{:?}", f.hinges); + assert!(f.collisions.is_empty(), "the stacked flaps and the glue flap do not cross: {:?}", f.collisions); + assert_eq!(f.order.first(), Some(&f.base)); + assert_eq!(f.order.len(), 13); +} + +#[test] +fn at_amount_0_the_blank_is_flat() { + let (b, _) = check(¬ched_box()); + let f = fold(&b[0], None, 0.0, TOL).expect("folds"); + for p in &f.panels { + for (row, want) in p.pose.m.iter().zip(Pose::IDENTITY.m) { + assert!(row.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", p.pose); + } + assert!(p.pose.t.iter().all(|v| v.abs() < 1e-9), "{:?}", p.pose); + } +} + +/// A 100 × 60 rectangle split by a line of `kind` at x = 60 (drawn upward when `up`), turned by +/// `quarter` quarter turns about the origin and mirrored in x when `mirror`. +fn two_panels(kind: LineKind, quarter: u8, mirror: bool, up: bool) -> Vec { + let at = |(x, y): (f64, f64)| { + let x = if mirror { -x } else { x }; + (0..quarter).fold((x, y), |(x, y), _| (-y, x)) + }; + let outline: Vec<(f64, f64)> = [(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)].into_iter().map(at).collect(); + let (a, b) = if up { ((60.0, 60.0), (60.0, 0.0)) } else { ((60.0, 0.0), (60.0, 60.0)) }; + vec![cut(&outline, 1), line(kind, &[at(a), at(b)], false, 2)] +} + +#[test] +fn a_crease_folds_away_from_the_print_and_a_partial_cut_toward_it_however_it_is_drawn() { + for quarter in 0..4 { + for mirror in [false, true] { + for up in [false, true] { + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::Perforation, -1.0), (LineKind::PartialCut, 1.0)] { + let case = format!("{kind:?}, {quarter} quarter turns, mirrored {mirror}, drawn up {up}"); + let (b, issues) = check(&two_panels(kind, quarter, mirror, up)); + assert!(issues.is_empty(), "{case}: {issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let h = &b.hinges[0]; + let hinge = [(h.from.x + h.to.x) / 2.0, -(h.from.y + h.to.y) / 2.0, 0.0]; + let c = flat_center(b, child); + let away = [c[0] - hinge[0], c[1] - hinge[1], 0.0]; + let along = [h.to.x - h.from.x, h.from.y - h.to.y]; + let off_line = (along[0] * away[1] - along[1] * away[0]).abs() / along[0].hypot(along[1]); + let placed = f.panels[child].pose.apply(c); + // The child stands up out of the plane: behind it for a crease, in front of it + // for a partial cut, at its distance from the hinge. + assert!(placed[2] * sign > 0.0, "{case}: {placed:?}"); + assert!((placed[2].abs() - off_line).abs() < 1e-6, "{case}: {placed:?} {off_line}"); + // Its printed side faces away from the base panel after a crease, back toward + // it after a partial cut. + let n = f.panels[child].pose.normal(); + assert!((n[0] * away[0] + n[1] * away[1]) * -sign > 0.0, "{case}: {n:?}"); + // Half way, the child is half way round. + let half = fold(b, None, 0.5, TOL).expect("folds"); + let z = half.panels[child].pose.normal()[2]; + assert!((z - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{case}: {z}"); + } + } + } + } +} + +/// A 100 × 100 square divided into four panels by a crease across it each way. +fn crossed() -> Vec { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + crease((50.0, 0.0), (50.0, 100.0), 2), + crease((0.0, 50.0), (100.0, 50.0), 3), + ] +} + +#[test] +fn a_loop_of_hinges_closes_when_flat_and_reports_its_gap_when_folded() { + let (b, issues) = check(&crossed()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (4, 4)); + let folded = fold(b, None, 1.0, TOL).expect("folds"); + let closing: Vec<&FoldedHinge> = folded.hinges.iter().filter(|h| !h.tree).collect(); + assert_eq!(closing.len(), 1, "three hinges make the tree, one closes the loop"); + assert!(!closing[0].closes && closing[0].gap > 10.0, "{closing:?}"); + // The gap is measured folded all the way, whatever the amount: flat or half way, the loop is + // still reported open by the same gap. + for amount in [0.0, 0.5] { + let part = fold(b, None, amount, TOL).expect("folds"); + let h = part.hinges.iter().find(|h| !h.tree).expect("a closing hinge"); + assert!(!h.closes && (h.gap - closing[0].gap).abs() < 1e-9, "{amount}: {h:?}"); + } + // The base is the top-left panel: four equal panels tie, and the highest, then leftmost, wins. + assert_eq!(b.panels[folded.base].outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((0.0, 0.0))); +} + +#[test] +fn hinges_that_start_at_one_point_fold_the_same_in_any_line_order() { + // About the bottom-right panel, its two hinges both start at the middle of the square. + let lines = crossed(); + let orders = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [1, 2, 0], [1, 0, 2], [2, 0, 1]]; + let mut seen = None; + for order in orders { + let lines: Vec = order.iter().map(|&i| lines[i].clone()).collect(); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{order:?}: {issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(75.0, 75.0)).expect("the bottom-right panel"); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + let closing = f.hinges.iter().zip(&b.hinges).find(|(h, _)| !h.tree).map(|(_, h)| ((h.from.x + h.to.x) / 2.0, (h.from.y + h.to.y) / 2.0)); + let top_left = panel_at(b, p(25.0, 25.0)).expect("the top-left panel"); + let placed = f.panels[top_left].pose.place(p(25.0, 25.0)).map(|v| (v * 1e6).round()); + let got = (closing, placed); + assert_eq!(seen.get_or_insert(got), &got, "{order:?}"); + } +} + +/// A 100 × 60 rectangle: the left 60 pt is one panel, the right is split across at y = 30, and the +/// line between them bends by `lean` pt over its lower half. +fn leaning(lean: f64) -> Vec { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + crease((60.0, 0.0), (60.0, 30.0), 2), + crease((60.0, 30.0), (60.0 + lean, 60.0), 3), + crease((60.0, 30.0), (100.0, 30.0), 4), + ] +} + +#[test] +fn a_loop_closes_within_the_tolerance_or_half_a_percent_of_its_hinge() { + // Both right panels turn about one line, so the hinge between them closes exactly. + let gap = |lean: f64, amount: f64| { + let (b, issues) = check(&leaning(lean)); + assert!(issues.is_empty(), "{lean}: {issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (3, 3)); + let base = panel_at(b, p(30.0, 30.0)).expect("the left panel"); + let f = fold(b, Some(base), amount, TOL).expect("folds"); + let h = f.hinges.iter().find(|h| !h.tree).expect("a closing hinge").clone(); + (h.closes, h.gap) + }; + let (closes, at) = gap(0.0, 1.0); + assert!(closes && at < 1e-9, "{at}"); + // A small lean opens it by more than the 0.1 pt tolerance but less than 0.5% of its 40 pt + // length (0.2 pt): still closed. + let (closes, at) = gap(0.1, 1.0); + assert!(closes && at > TOL && at <= 0.2, "{at}"); + // A larger lean opens it past both, flat or folded. + for amount in [0.0, 1.0] { + let (closes, at) = gap(1.0, amount); + assert!(!closes && at > 0.2, "{amount}: {at}"); + } +} + +#[test] +fn a_panel_no_hinge_joins_stays_flat_where_it_is() { + let lines = vec![ + cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1), + crease((50.0, 49.95), (50.0, 50.0), 2), + ]; + let (b, _) = check(&lines); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (2, 0)); + let f = fold(b, None, 1.0, TOL).expect("folds"); + let loose = 1 - f.base; + assert_eq!(f.panels[loose].parent, None); + assert_eq!(f.panels[loose].pose, Pose::IDENTITY); + assert_eq!(f.order, vec![f.base, loose], "the loose panel comes last"); +} + +#[test] +fn a_child_of_a_notched_panel_folds_away_from_the_print() { + // The base is an L: a 30 × 140 strip with an 80 pt arm along its top running right to x = 300. + // The child, below the arm past a 2 pt slot, is hinged to the strip along x = 30. + let lines = vec![ + cut(&[(0.0, 0.0), (300.0, 0.0), (300.0, 80.0), (30.0, 80.0), (30.0, 82.0), (300.0, 82.0), (300.0, 140.0), (0.0, 140.0)], 1), + crease((30.0, 82.0), (30.0, 140.0), 2), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(15.0, 110.0)).expect("the L"); + let child = panel_at(b, p(150.0, 110.0)).expect("the child"); + // The L's inside point lies in its arm, on the child's side of the hinge's line. + let inside = b.panels[base].point_inside().expect("a point inside"); + assert!(inside.x > 30.0, "{inside:?}"); + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::PartialCut, 1.0)] { + let mut lines = lines.clone(); + lines[1].kind = kind; + let (b, _) = check(&lines); + let f = fold(&b[0], Some(base), 1.0, TOL).expect("folds"); + let placed = f.panels[child].pose.place(p(150.0, 110.0)); + assert!(placed[2] * sign > 99.0, "{kind:?}: {placed:?}"); + } +} + +#[test] +fn a_lid_folded_over_the_base_crosses_the_taller_wall_opposite() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. + let lines = vec![ + cut(&[(0.0, 0.0), (310.0, 0.0), (310.0, 50.0), (0.0, 50.0)], 1), + crease((120.0, 0.0), (120.0, 50.0), 2), + crease((150.0, 0.0), (150.0, 50.0), 3), + crease((250.0, 0.0), (250.0, 50.0), 4), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(200.0, 25.0)).expect("the base panel"); + let (lid, wall) = (panel_at(b, p(60.0, 25.0)).unwrap(), panel_at(b, p(280.0, 25.0)).unwrap()); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + assert_eq!(f.collisions, vec![(lid.min(wall), lid.max(wall))]); + // Half folded, nothing crosses yet. + assert!(fold(b, Some(base), 0.4, TOL).expect("folds").collisions.is_empty()); +} + +#[test] +fn the_base_is_the_panel_under_a_point_and_the_same_in_any_input_order() { + let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), crease((50.0, 0.0), (50.0, 60.0), 2)]; + let (b, _) = check(&lines); + assert_eq!(panel_at(&b[0], p(500.0, 500.0)), None, "a point outside every panel"); + let right = panel_at(&b[0], p(75.0, 30.0)).expect("the right panel"); + assert_eq!(fold(&b[0], Some(right), 1.0, TOL).expect("folds").base, right); + let mut reversed = lines.clone(); + reversed.reverse(); + let (r, _) = check(&reversed); + for blank in [&b[0], &r[0]] { + let f = fold(blank, None, 1.0, TOL).expect("folds"); + // Equal panels: the leftmost wins. + assert_eq!(blank.panels[f.base].outline.bounds().map(|r| r.x0.round()), Some(0.0)); + } + assert!(fold(&b[0], Some(9), 1.0, TOL).is_none(), "no panel 9"); + assert!(fold(&b[0], None, 1.5, TOL).is_none(), "past 1"); + assert!(fold(&b[0], None, f64::NAN, TOL).is_none()); + assert!(fold(&Blank::default(), None, 1.0, TOL).is_none(), "no panels"); +} + +#[test] +fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { + let (b, _) = check(&two_panels(LineKind::PartialCut, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, -90.0); + let (b, _) = check(&two_panels(LineKind::Perforation, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, 90.0); + // A crease and a short partial cut on one line: the crease is the longer piece. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + line(LineKind::PartialCut, &[(60.0, 0.0), (60.0, 10.0)], false, 2), + crease((60.0, 10.0), (60.0, 60.0), 3), + ]; + let (b, _) = check(&lines); + assert_eq!(b[0].hinges.len(), 1); + assert_eq!(b[0].hinges[0].angle, 90.0); } diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 18d371b420..c6b00ed851 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -13,7 +13,7 @@ mod solid; mod visibility; pub use solid::{ Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, - extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, + extrude_mesh_face, extrude_side_size, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; @@ -389,7 +389,9 @@ pub struct Face { pub plane: Option, } -/// Where a face of Revolve's swept side lies on the side surface, unrolled flat: x runs around the +/// Where a face of a side surface lies on it unrolled flat, for the graphics mapped onto it. On +/// Extrude & Bevel's side ([`Facet::surface`]) x runs along the outline and y from the front toward +/// the back. On Revolve's swept side x runs around the /// axis and y along the profile, in points. x is the angle from the middle of the surface times the /// point's own distance from the axis, so a graphic keeps its size at every distance and wraps /// farther around the axis where the profile comes closer to it. y is the length along the profile diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index cc8881d2d9..5029a79910 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -19,6 +19,7 @@ mod inflate; mod membrane; mod outline; mod rings; +mod side; #[cfg(test)] pub(crate) use build::EXTRUDED; @@ -27,7 +28,7 @@ pub(crate) use build::PLANES; #[cfg(test)] use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; -pub use build::{extrude, plane}; +pub use build::{extrude, extrude_side_size, plane}; pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; #[cfg(test)] use inflate::GRID_WORK; @@ -218,11 +219,14 @@ pub struct Extrude { /// Keep the faces of a closed solid that are turned away from the viewer (Draw Hidden Faces, /// and the classic Wireframe surface), drawn behind the faces turned toward it. pub hidden: bool, + /// Graphics are mapped onto the side: the pieces of the walls and bevels of the solid's longest + /// contour carry a [`Facet::surface`]. Off by default, which leaves the facets without one. + pub map_surface: bool, } impl Default for Extrude { fn default() -> Self { - Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false } + Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surface: false } } } @@ -249,21 +253,24 @@ impl Default for Inflate { } } -/// A planar face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the -/// art itself, or a plane's only face) or its back cap. +/// A face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the art itself, +/// or a plane's only face), its back cap, or its side (the walls and bevels, unrolled flat: +/// [`Facet::surface`]). Only the caps are planar. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PlanarFace { Front, Back, + Side, } impl PlanarFace { - pub const ALL: [PlanarFace; 2] = [Self::Front, Self::Back]; + pub const ALL: [PlanarFace; 3] = [Self::Front, Self::Back, Self::Side]; pub fn id(self) -> &'static str { match self { Self::Front => "front", Self::Back => "back", + Self::Side => "side", } } @@ -296,6 +303,10 @@ pub struct Facet { /// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane /// (its front). `None` for every other facet. pub end: Option, + /// For a piece of Extrude & Bevel's side built for graphics ([`Extrude::map_surface`]): where + /// its corners lie on the side unrolled flat, for a graphic mapped onto it. x runs along the + /// outline and y from the front toward the back ([`crate::SurfaceCell`]). + pub surface: Option, /// The face's plane in view space and the projection it was drawn with, for its depth at a /// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than /// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye. @@ -384,6 +395,8 @@ impl Facet { // A revolved cap is not one of the planar faces graphics map onto. end: None, away: false, + // Revolve's graphics are drawn from its faces, before they become facets. + surface: None, plane: face.plane, #[cfg(test)] view: vec![], diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d734161343..29d5debcc3 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -5,6 +5,7 @@ use super::rings::{ CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area, solid_rings_traced, square_corners, }; +use super::side; use super::{ Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, eye_distance, perspective_scale, @@ -211,6 +212,7 @@ impl<'a> Builder<'a> { side: false, away: behind, end: None, + surface: None, plane, #[cfg(test)] view, @@ -249,11 +251,13 @@ impl<'a> Builder<'a> { /// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the /// direction (before rotation) the band faces away from the solid, for orienting normals. pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> { - self.curved_band(a, b, cuts, outward, None) + self.curved_band(a, b, cuts, outward, None, None) } /// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the /// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved. + /// With `side`, each quad carries where its corners lie on the side unrolled flat + /// ([`Facet::surface`]). pub(super) fn curved_band( &mut self, a: &[V3], @@ -261,6 +265,7 @@ impl<'a> Builder<'a> { cuts: &[usize], outward: impl Fn(usize) -> V3, mut curves: Option, + side: Option, ) -> Result<(), String> { let n = a.len().min(b.len()); // At 0 and 1, the corners themselves. @@ -295,6 +300,21 @@ impl<'a> Builder<'a> { && let Some(f) = self.facets.last_mut() { f.side = true; + if let Some(s) = side.as_ref() + && let (Some([x0, x1]), Some(page)) = (s.x.get(i).copied(), f.contours.first()) + { + let (u0, u1) = (x0 + (x1 - x0) * s0, x0 + (x1 - x0) * s1); + let [y0, y1] = s.y; + // The face shows the side's outside when it was neither turned around to + // show its inside (on a hollow solid) nor kept turned away. + let n = normal.unit(); + let outward = !f.away && f.normal[0] * n.0 + f.normal[1] * n.1 + f.normal[2] * n.2 > 0.0; + f.surface = Some(crate::SurfaceCell { + page: page.clone(), + uv: vec![Point::new(u0, y0), Point::new(u1, y0), Point::new(u1, y1), Point::new(u0, y1)], + outward, + }); + } } if let Some(w) = curves.as_mut().filter(|_| pieces == 1) && let Some(span) = w.spans.get(i).copied().flatten() @@ -353,6 +373,13 @@ pub(super) struct WallCurves<'a> { pub(super) budget: &'a mut Budget, } +/// Where a band of the side lies on the side unrolled flat ([`super::side`]): the x of each end of +/// each edge of its rings, and the y of its two rings. +pub(super) struct SideBand<'a> { + pub(super) x: &'a [[f64; 2]], + pub(super) y: [f64; 2], +} + /// Where a point of the art goes in view space at one step: [`Camera::place`] after a [`Turn`], /// at depth `z`, as one affine map worked out once for the step. pub(super) struct Placing { @@ -667,7 +694,17 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio }) .collect(); let mut budget = Budget::default(); - for ((ring, traced), pieces) in rings.iter().zip(&traced).zip(&pieces) { + // With graphics on the side, the longest contour's pieces carry where they lie on it unrolled. + let unrolled = o + .map_surface + .then(|| { + let k = side::longest(&rings)?; + let y = side::across_steps(&steps.iter().map(|s| (s.inset, s.t)).collect::>(), o.depth); + Some((k, side::along_ring(rings.get(k)?)?, y)) + }) + .flatten(); + for (r, ((ring, traced), pieces)) in rings.iter().zip(&traced).zip(&pieces).enumerate() { + let unrolled = unrolled.as_ref().filter(|(k, ..)| *k == r); let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); for (k, pair) in placed.windows(2).enumerate() { let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue }; @@ -684,7 +721,8 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio // stay straight, within the sampling tolerance. let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len())); let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget }); - b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves)?; + let side = unrolled.and_then(|(_, x, y)| Some(SideBand { x, y: [*y.get(k)?, *y.get(k + 1)?] })); + b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; } } if o.cap { @@ -705,6 +743,31 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Ok(b.finish()) } +/// The size of Extrude & Bevel's side unrolled flat ([`super::side`]), for a solid of `path` built +/// as [`extrude`] builds it: the length of its longest contour's outline, the length across its +/// bevels and walls, front to back, and the width about x = 0 that does not reach the side's cut. +/// `None` with a depth of 0, for invalid bounds, and for a shape [`extrude`] refuses. +pub fn extrude_side_size(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude) -> Option<(f64, f64, f64)> { + check_bounds(bounds).ok()?; + let o = options.sanitized(); + if o.depth <= 0.0 { + return None; + } + let steps = steps(&o); + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); + let size = bounds.width().max(bounds.height()); + let most = curve_pieces(path, size, bands, caps).ok()?; + let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); + let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most).ok()?.iter().map(|r| square_corners(r, side)).collect(); + let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); + // A solid past the face limit is refused, as [`extrude_faces`] refuses it. + let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); + if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { + return None; + } + side::size(&rings, &steps.iter().map(|s| (s.inset, s.t)).collect::>(), o.depth) +} + #[cfg(test)] thread_local! { /// How many Rotate planes (and Extrude & Bevel solids with no depth) this thread has built, for diff --git a/crates/three-d/src/solid/face_map.rs b/crates/three-d/src/solid/face_map.rs index ac99348ba3..51a6709df0 100644 --- a/crates/three-d/src/solid/face_map.rs +++ b/crates/three-d/src/solid/face_map.rs @@ -145,7 +145,8 @@ impl FaceMap { /// The map of Extrude & Bevel's cap `face` for a solid built with `bounds`, `options` and `view`, /// as [`super::extrude`] builds it. With a depth of 0 the art is a plane, whose only face is the -/// front. `None` for a hollow solid (no caps), for the back of a plane, and for invalid bounds. +/// front. `None` for a hollow solid (no caps), for the back of a plane, for the side (which is not +/// planar), and for invalid bounds. pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option { check_bounds(bounds).ok()?; let o = options.sanitized(); @@ -159,6 +160,7 @@ pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: Planar let (t, side) = match face { PlanarFace::Front => (0.0, 1.0), PlanarFace::Back => (1.0, -1.0), + PlanarFace::Side => return None, }; let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); let at = placing.place(bounds.center()); @@ -235,7 +237,7 @@ impl MeshFace { /// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with /// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0 /// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane, -/// and for invalid bounds. +/// for the side, and for invalid bounds. pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option { check_bounds(bounds).ok()?; let o = options.sanitized(); @@ -249,6 +251,7 @@ pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: Plana let (t, side) = match face { PlanarFace::Front => (0.0, 1.0), PlanarFace::Back => (1.0, -1.0), + PlanarFace::Side => return None, }; let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); Some(MeshFace::new(&camera, &placing, bounds.center(), side, false)) diff --git a/crates/three-d/src/solid/side.rs b/crates/three-d/src/solid/side.rs new file mode 100644 index 0000000000..2a285246ec --- /dev/null +++ b/crates/three-d/src/solid/side.rs @@ -0,0 +1,133 @@ +//! Extrude & Bevel's side unrolled flat, for the graphics mapped onto it ([`super::Facet::surface`]). +//! +//! x runs along the outline of the solid's longest contour, through its corners and curves, and y +//! runs from the front cap's edge toward the back cap's, across the bevels and the walls. Both are +//! lengths in points: x along the art's own outline (the front cap's edge, or with a bevel carved +//! into the shape the walls' outline), y along the outline's steps (the slant +//! of each bevel step and the depth of the walls), before the twist and the taper, which carry the +//! graphic with the side. x is 0 where the contour's top crosses the vertical line through the +//! middle of its bounds and grows clockwise around the outline as the front is seen on the page, so +//! a graphic reads the right way round from outside the side. y is 0 half way along the steps. The +//! side is cut at the anchor of the contour nearest half way around from x = 0. + +use super::rings::signed_area; +use super::{Point, Rect}; + +/// The length of the outline of `ring`. +fn perimeter(ring: &[Point]) -> f64 { + ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(a, b)| a.distance(*b)).sum() +} + +/// The ring of `rings` with the longest outline (the first of equal ones), which carries the side's +/// graphics. `None` when no ring has a finite length above 0. +pub(super) fn longest(rings: &[&[Point]]) -> Option { + rings + .iter() + .map(|r| perimeter(r)) + .enumerate() + .filter(|(_, l)| l.is_finite() && *l > 0.0) + .fold(None, |best: Option<(usize, f64)>, (k, l)| if best.is_some_and(|(_, top)| top >= l) { best } else { Some((k, l)) }) + .map(|(k, _)| k) +} + +/// The x of each end of each edge of `ring` (point `i` to point `i + 1`, the last back to the first), +/// as the module describes. `None` for a ring with no length or bounds that are not finite. +pub(super) fn along_ring(ring: &[Point]) -> Option> { + let n = ring.len(); + if n < 2 { + return None; + } + let edges = || ring.iter().zip(ring.iter().cycle().skip(1)).map(|(a, b)| (*a, *b)); + let lengths: Vec = edges().map(|(a, b)| a.distance(b)).collect(); + let total: f64 = lengths.iter().sum(); + if !total.is_finite() || total <= 0.0 { + return None; + } + let mut starts = Vec::with_capacity(n); + let mut at = 0.0; + for l in &lengths { + starts.push(at); + at += l; + } + let bounds = ring.iter().fold(None, |b: Option, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?; + let middle = bounds.center().x; + // Where x = 0: the crossing of the middle line nearest the top, as a length along the ring. + let mut origin: Option<(f64, f64)> = None; + let mut keep = |y: f64, s: f64| { + if origin.is_none_or(|(top, _)| y < top) { + origin = Some((y, s)); + } + }; + for ((a, b), (s, l)) in edges().zip(starts.iter().zip(&lengths)) { + if (a.x - middle) * (b.x - middle) > 0.0 { + continue; + } + if a.x == b.x { + // An edge along the middle line: its upper end. + if a.y <= b.y { keep(a.y, *s) } else { keep(b.y, s + l) } + } else { + let t = (middle - a.x) / (b.x - a.x); + keep(a.y + (b.y - a.y) * t, s + l * t); + } + } + let (_, origin) = origin?; + // The cut: the anchor nearest half way around from the origin. + let opposite = (origin + total / 2.0).rem_euclid(total); + let round = |d: f64| { + let d = d.rem_euclid(total); + d.min(total - d) + }; + let cut = starts + .iter() + .copied() + .fold(None, |best: Option, s| if best.is_some_and(|b| round(b - opposite) <= round(s - opposite)) { best } else { Some(s) })?; + let from_cut = (origin - cut).rem_euclid(total); + // The ring runs clockwise on the page (y down) when it encloses positive area: x grows along it. + let sign = if signed_area(ring) >= 0.0 { 1.0 } else { -1.0 }; + Some( + starts + .iter() + .zip(&lengths) + .map(|(s, l)| { + let a = (s - cut).rem_euclid(total) - from_cut; + [a * sign, (a + l) * sign] + }) + .collect(), + ) +} + +/// The y of each of an extrusion's `steps`, each its inset (points) and its depth fraction (0 front, +/// 1 back) of a solid `depth` points deep: the length along the steps from their middle, growing +/// toward the back. +pub(super) fn across_steps(steps: &[(f64, f64)], depth: f64) -> Vec { + let mut out = Vec::with_capacity(steps.len()); + let mut at = 0.0; + for (k, (inset, t)) in steps.iter().enumerate() { + if let Some((i0, t0)) = k.checked_sub(1).and_then(|k| steps.get(k)) { + at += (inset - i0).hypot(depth * (t - t0)); + } + out.push(at); + } + let middle = at / 2.0; + out.into_iter().map(|y| y - middle).collect() +} + +/// The size of Extrude & Bevel's side unrolled, around the longest of `rings` and across the steps +/// `steps` (each inset and depth fraction) of a solid `depth` points deep: the length around it, +/// the length across it, and the width about x = 0 that does not reach the side's cut (twice the +/// distance from x = 0 to the nearer end of the cut side). `None` when the side has no length +/// either way. +pub(super) fn size(rings: &[&[Point]], steps: &[(f64, f64)], depth: f64) -> Option<(f64, f64, f64)> { + let ring = rings.get(longest(rings)?)?; + let across = across_steps(steps, depth); + let height = across.last().zip(across.first()).map_or(0.0, |(b, a)| b - a); + let width = perimeter(ring); + let xs = along_ring(ring)?; + let (lo, hi) = xs.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + let span = 2.0 * (-lo).min(hi); + (width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0).then_some((width, height, span.clamp(0.0, width))) +} + +#[cfg(test)] +#[path = "tests_side.rs"] +mod tests; diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 0d9566e5e5..b32faf1097 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -438,9 +438,11 @@ fn malformed_and_degenerate_input_is_bounded() { cap: true, bevel: Some(Bevel { width: f64::NAN, height: 1e12, repeat: usize::MAX, space: 7.0, ..Bevel::default() }), hidden: false, + map_surface: true, }; let f = extrude(&p, FillRule::EvenOdd, b, wild, View { rotation_x: f64::NAN, perspective: 900.0, ..front() }).unwrap(); assert!(f.iter().flat_map(|f| f.contours.iter().flatten()).all(|q| q.x.is_finite() && q.y.is_finite())); + assert!(f.iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter()).all(|q| q.x.is_finite() && q.y.is_finite())); assert!( inflate( &p, diff --git a/crates/three-d/src/solid/tests_side.rs b/crates/three-d/src/solid/tests_side.rs new file mode 100644 index 0000000000..f2d7ec722a --- /dev/null +++ b/crates/three-d/src/solid/tests_side.rs @@ -0,0 +1,96 @@ +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; + +use super::super::{Bevel, Extrude, View, extrude, extrude_side_size}; +use super::{across_steps, along_ring, longest}; + +fn square(r: Rect, hole: Option) -> PathData { + let mut b = BezPath::new(); + b.move_to((r.x0, r.y0)); + b.line_to((r.x1, r.y0)); + b.line_to((r.x1, r.y1)); + b.line_to((r.x0, r.y1)); + b.close_path(); + if let Some(h) = hole { + b.move_to((h.x0, h.y0)); + b.line_to((h.x0, h.y1)); + b.line_to((h.x1, h.y1)); + b.line_to((h.x1, h.y0)); + b.close_path(); + } + PathData::from_bezpath(&b) +} + +/// x is 0 at the top of the middle line and grows clockwise on the page; the side is cut at the +/// anchor nearest half way around (the first of two equally near). +#[test] +fn x_runs_clockwise_from_the_top_middle() { + let ring = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + assert_eq!(along_ring(&ring).unwrap(), vec![[-5.0, 5.0], [5.0, 15.0], [-25.0, -15.0], [-15.0, -5.0]]); + // The same outline run the other way gives each point the same x, apart from the seam, which + // is now at (0, 10), its first anchor of the two equally near. + let back: Vec = ring.iter().rev().copied().collect(); + let x = along_ring(&back).unwrap(); + assert_eq!(x, vec![[25.0, 15.0], [15.0, 5.0], [5.0, -5.0], [-5.0, -15.0]]); + assert_eq!(along_ring(&[Point::ZERO, Point::ZERO]), None); +} + +#[test] +fn y_runs_across_the_steps_from_their_middle() { + // A 4 × 3 pt bevel step, then 20 pt of wall, on a solid 30 pt deep. + let y = across_steps(&[(0.0, 0.0), (-4.0, 0.1), (-4.0, 0.1 + 20.0 / 30.0)], 30.0); + let expected = [-12.5, -7.5, 12.5]; + for (a, b) in y.iter().zip(expected) { + assert!((a - b).abs() < 1e-9, "{y:?}"); + } +} + +/// With graphics on the side, every piece of the walls of the longest contour carries its place on +/// the side unrolled, and no other facet does: x along the outline and y from the front to the back. +#[test] +fn the_longest_contours_walls_carry_their_place_on_the_side() { + let (outer, inner) = (Rect::new(0.0, 0.0, 100.0, 60.0), Rect::new(30.0, 20.0, 70.0, 40.0)); + let path = square(outer, Some(inner)); + let o = Extrude { depth: 40.0, map_surface: true, ..Extrude::default() }; + // Seen from above: the top wall faces the viewer and keeps its x on the page. + let top = View { rotation_x: -90.0, ..View::default() }; + let facets = extrude(&path, FillRule::NonZero, outer, o, top).unwrap(); + let cells: Vec<_> = facets.iter().filter_map(|f| f.surface.as_ref().map(|c| (f, c))).collect(); + assert!(!cells.is_empty()); + assert!(cells.iter().all(|(f, c)| f.side && f.end.is_none() && c.uv.len() == 4 && c.page.len() == 4)); + let seen: Vec<_> = cells.iter().filter(|(_, c)| c.outward).collect(); + assert_eq!(seen.len(), 1, "only the top wall of the outline faces the viewer"); + for (_, c) in seen { + for (uv, page) in c.uv.iter().zip(&c.page) { + assert!((page.x - (50.0 + uv.x)).abs() < 1e-6, "{uv:?} {page:?}"); + assert!(uv.y.abs() <= 20.0 + 1e-9); + } + } + // Only the outline's top wall is drawn (the walls seen edge-on have no area on the page, and the + // bottom wall faces away); the hole's walls carry none. Without graphics no facet carries one. + assert_eq!(cells.len(), 1); + let turned = View { rotation_x: -60.0, rotation_y: 30.0, ..View::default() }; + let hollow = extrude(&path, FillRule::NonZero, outer, Extrude { cap: false, ..o }, turned).unwrap(); + let hollow: Vec<_> = hollow.iter().filter_map(|f| f.surface.as_ref()).collect(); + // A hollow solid shows the insides of its far walls: they carry a cell that is not outward. + assert!(hollow.iter().any(|c| c.outward) && hollow.iter().any(|c| !c.outward), "{}", hollow.len()); + let plain = extrude(&path, FillRule::NonZero, outer, Extrude { map_surface: false, ..o }, top).unwrap(); + assert!(plain.iter().all(|f| f.surface.is_none())); + assert_eq!(plain.len(), facets.len()); +} + +#[test] +fn the_side_measures_around_the_outline_and_across_the_bevels() { + let outer = Rect::new(0.0, 0.0, 100.0, 60.0); + let path = square(outer, None); + let plain = Extrude { depth: 40.0, ..Extrude::default() }; + // The cut is at a bottom corner, 110 pt each way from the top's middle: 220 pt about x = 0 + // stay clear of it. + assert_eq!(extrude_side_size(&path, FillRule::NonZero, outer, plain), Some((320.0, 40.0, 220.0))); + // A 3 × 4 pt classic bevel outside adds its 5 pt slant and takes 4 pt of the wall. + let bevel = Extrude { bevel: Some(Bevel { width: 3.0, height: 4.0, ..Bevel::default() }), ..plain }; + let (w, h, span) = extrude_side_size(&path, FillRule::NonZero, outer, bevel).unwrap(); + assert!((w - 320.0).abs() < 1e-9 && (h - 41.0).abs() < 1e-9 && (span - 220.0).abs() < 1e-9, "{w} {h} {span}"); + assert_eq!(extrude_side_size(&path, FillRule::NonZero, outer, Extrude { depth: 0.0, ..plain }), None); + let rings = [&[Point::ZERO, Point::new(1.0, 0.0), Point::new(0.0, 1.0)][..], &[Point::ZERO, Point::new(5.0, 0.0), Point::new(0.0, 5.0)][..]]; + assert_eq!(longest(&rings), Some(1)); +} diff --git a/crates/tools/src/addons/anchor_eraser.rs b/crates/tools/src/addons/anchor_eraser.rs index 1eae255bc2..114e2b8e7a 100644 --- a/crates/tools/src/addons/anchor_eraser.rs +++ b/crates/tools/src/addons/anchor_eraser.rs @@ -152,6 +152,16 @@ impl Tool for AnchorEraserTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "size" => c::number(key, v, SIZE_RANGE.0, SIZE_RANGE.1), + "tolerance" => c::number(key, v, TOLERANCE_RANGE.0, TOLERANCE_RANGE.1), + "pressure" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index b0ecdc350e..e4f4b272c5 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -729,4 +729,33 @@ impl Tool for Box3dTool { _ => {} } } + + /// The options within their ranges. Any finite arc angle is taken: it is kept from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let max_radius = crate::shape::MAX_CORNER_RADIUS; + match key { + "shape" => c::one_of(key, v, &["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"]), + "cornerRadius" => c::number(key, v, 0.0, max_radius), + "cornerRadii" => { + let radii = v.as_array().filter(|a| a.len() == 4); + if radii.is_some_and(|a| a.iter().all(|r| r.as_f64().is_some_and(|r| r.is_finite() && (0.0..=max_radius).contains(&r)))) { + Ok(()) + } else { + Err(format!("`cornerRadii` must be four numbers from 0 to {max_radius}")) + } + } + "arcStart" | "arcEnd" => c::finite(key, v), + "arcMode" => c::one_of(key, v, &["whole", "pie", "chord", "arc"]), + "sides" | "points" => c::whole(key, v, 3, 1000), + "starRatio" => c::number(key, v, 0.01, 1.0), + "rounded" | "randomized" => c::number(key, v, -10.0, 10.0), + "turns" => c::number(key, v, 0.01, 1024.0), + "divergence" => c::number(key, v, 0.0, 1000.0), + "innerRadius" => c::number(key, v, 0.0, 0.999), + "angleX" | "angleY" | "angleZ" => c::number(key, v, -180.0, 180.0), + "cornerSymmetry" | "polyIsStar" | "clockwise" | "parallelX" | "parallelY" | "parallelZ" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } diff --git a/crates/tools/src/addons/contour.rs b/crates/tools/src/addons/contour.rs index e77bb29eed..3bac5a6649 100644 --- a/crates/tools/src/addons/contour.rs +++ b/crates/tools/src/addons/contour.rs @@ -248,6 +248,15 @@ impl Tool for ContourTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "corners" if value.as_str().and_then(Corners::parse).is_some() => Ok(()), + "corners" => Err("`corners` must be one of `sharp`, `round`, `square`".into()), + "miterLimit" => crate::option_check::number(key, value, 1.0, 500.0), + _ => Err(crate::option_check::unknown(key)), + } + } + fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/addons/corner_tool.rs b/crates/tools/src/addons/corner_tool.rs index 470795579e..05ec27b18b 100644 --- a/crates/tools/src/addons/corner_tool.rs +++ b/crates/tools/src/addons/corner_tool.rs @@ -382,6 +382,16 @@ impl Tool for CornerTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "radius" => c::number(key, v, 0.0, MAX_RADIUS), + "kind" if serde_json::from_value::(v.clone()).is_ok() => Ok(()), + "kind" => Err("`kind` must be one of `round`, `invertedRound`, `chamfer`".into()), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/enclosing_lasso.rs b/crates/tools/src/addons/enclosing_lasso.rs index 0f674aead9..e8b228f86f 100644 --- a/crates/tools/src/addons/enclosing_lasso.rs +++ b/crates/tools/src/addons/enclosing_lasso.rs @@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool { let symbols = cx.doc.symbol_boxes(); let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten(); let mut ids = if let Some(region) = region { - enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline) + enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline, !cx.guides) .into_iter() .filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion))) .collect() diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs index 816000ac9f..e844da9130 100644 --- a/crates/tools/src/addons/extend_path.rs +++ b/crates/tools/src/addons/extend_path.rs @@ -203,6 +203,14 @@ impl Tool for ExtendPathTool { self.mode = Mode(m); } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key != "mode" { + return Err(crate::option_check::unknown(key)); + } + let ids: Vec<&str> = ExtendMode::ALL.iter().map(|m| m.id()).collect(); + crate::option_check::one_of(key, v, &ids) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/parametric_shape.rs b/crates/tools/src/addons/parametric_shape.rs index 33700073c7..e651f5399b 100644 --- a/crates/tools/src/addons/parametric_shape.rs +++ b/crates/tools/src/addons/parametric_shape.rs @@ -475,6 +475,32 @@ impl Tool for ParametricShapeTool { self.next = s; } } + + /// The numbers [`Self::options`] shows, each as [`apply`] checks it; null is not a value. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if self.options().get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + apply(self.next, &json!({ key: v })).map(|_| ()) + } + + /// The options together, as [`apply`] takes them: a `kind` given with them sets the kind + /// first, and the other values are checked against that kind's ranges. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let options = self.options(); + for (key, v) in values { + if options.get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + } + apply(self.next, &Value::Object(values.clone())).map(|_| ()) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/shared_edge.rs b/crates/tools/src/addons/shared_edge.rs index d11261800a..703e8e6f3f 100644 --- a/crates/tools/src/addons/shared_edge.rs +++ b/crates/tools/src/addons/shared_edge.rs @@ -214,6 +214,16 @@ impl Tool for SharedEdgeTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, DIAMETER_RANGE.0, DIAMETER_RANGE.1), + "tolerance" => c::number(key, v, 0.0, MAX_COINCIDENCE), + "together" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 43269ed580..805e015159 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -625,6 +625,10 @@ impl Tool for SmartPenTool { } } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "next" { crate::option_check::one_of(key, v, &["curved", "straight"]) } else { Err(crate::option_check::unknown(key)) } + } } #[cfg(test)] diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index ea3324dc33..77ff240f75 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -858,6 +858,9 @@ impl Tool for ShapeBuilderTool { self.cache.clear(); self.cache.gap = self.gap(); } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_builder_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } /// Why `tool.setOption` cannot give the builder-family tool `tool` the options `values`, checked diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index caa9379308..c694240057 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -870,6 +870,10 @@ impl Tool for LivePaintBucketTool { self.hover = LpHover::None; } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } + fn waiting(&self) -> bool { self.cache.waiting() } @@ -1293,4 +1297,8 @@ impl Tool for LivePaintSelectionTool { } self.hover = LpHover::None; } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index 6b524e9af9..437ecde69a 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -519,6 +519,58 @@ pub fn sample_polyline(pts: &[Point], step: f64) -> Vec { out } +#[cfg(test)] +thread_local! { + /// The edges [`hatch`] has tested against a scanline on this thread. + pub(super) static HATCH_EDGE_TESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A region's edges in [`hatch`]'s rotated space, met in order of rising scanline. Each line tests +/// only the edges that span it, and the edges with a NaN or infinite end height. +pub(super) struct EdgeSweep { + /// The edges with finite, unequal end heights, by lower end. + edges: Vec<(Point, Point)>, + /// How many of `edges` have reached the active list. + next: usize, + /// The edges whose lower end is at or below the last line and whose upper end is above it. + active: Vec<(Point, Point)>, + /// The edges with a NaN or infinite end height. + loose: Vec<(Point, Point)>, +} + +impl EdgeSweep { + pub(super) fn new(mut edges: Vec<(Point, Point)>) -> Self { + let mut loose = vec![]; + edges.retain(|&(a, c)| { + let finite = a.y.is_finite() && c.y.is_finite(); + if !finite { + loose.push((a, c)); + } + // An edge with equal end heights never crosses a scanline. + finite && a.y != c.y + }); + edges.sort_unstable_by(|(a, c), (b, d)| a.y.min(c.y).total_cmp(&b.y.min(d.y))); + EdgeSweep { edges, next: 0, active: vec![], loose } + } + + /// Pushes the x of each edge crossing the scanline at `y` onto `xs`, in no particular order. + /// `y` is not NaN and never decreases from one call to the next. + pub(super) fn crossings(&mut self, y: f64, xs: &mut Vec) { + while let Some(&(a, c)) = self.edges.get(self.next).filter(|(a, c)| a.y.min(c.y) <= y) { + self.active.push((a, c)); + self.next += 1; + } + self.active.retain(|(a, c)| a.y.max(c.y) > y); + #[cfg(test)] + HATCH_EDGE_TESTS.with(|n| n.set(n.get() + self.active.len() + self.loose.len())); + for (a, c) in self.active.iter().chain(&self.loose) { + if (a.y <= y) != (c.y <= y) { + xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); + } + } + } +} + /// Diagonal hatch lines filling `path` (the Shape Builder's grey mesh highlight), `gap` apart. pub fn hatch(path: &BezPath, gap: f64) -> BezPath { let mut out = BezPath::new(); @@ -563,6 +615,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { } let gap = gap.max((y1 - y0) / 400.0).max(1e-6); let start = (y0 / gap).floor() * gap + gap * 0.5; + let mut sweep = EdgeSweep::new(edges); let mut xs: Vec = vec![]; // Counted, not summed: far from the origin `y + gap` can round back to `y`. The gap is at least // a 400th of the height, so 402 lines cover it. @@ -572,11 +625,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { break; } xs.clear(); - for (a, c) in &edges { - if (a.y <= y) != (c.y <= y) { - xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); - } - } + sweep.crossings(y, &mut xs); xs.sort_by(f64::total_cmp); for pair in xs.as_chunks::<2>().0 { out.move_to(unrot(Point::new(pair[0], y))); diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 219c0028f3..dc31c1ba79 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1133,6 +1133,275 @@ fn hatch_far_from_the_origin_ends() { assert!(hatch(&bp, 4.0).elements().len() <= 2 * 402); } +/// [`hatch`] as it tested every edge on every scanline, the reference the sweep must match. +fn hatch_every_edge(path: &BezPath, gap: f64) -> BezPath { + let mut out = BezPath::new(); + let b = path.bounding_box(); + if b.width() <= 0.0 || b.height() <= 0.0 { + return out; + } + let s = std::f64::consts::FRAC_1_SQRT_2; + let rot = |p: Point| Point::new((p.x + p.y) * s, (p.y - p.x) * s); + let unrot = |p: Point| Point::new((p.x - p.y) * s, (p.x + p.y) * s); + let mut edges: Vec<(Point, Point)> = vec![]; + let mut first = Point::ZERO; + let mut last = Point::ZERO; + kurbo::flatten(path.iter(), gap.max(1e-3) * 0.1, |el| match el { + kurbo::PathEl::MoveTo(p) => { + if last != first { + edges.push((rot(last), rot(first))); + } + first = p; + last = p; + } + kurbo::PathEl::LineTo(p) => { + edges.push((rot(last), rot(p))); + last = p; + } + kurbo::PathEl::ClosePath => { + if last != first { + edges.push((rot(last), rot(first))); + } + last = first; + } + _ => {} + }); + if last != first { + edges.push((rot(last), rot(first))); + } + let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); + for (a, c) in &edges { + y0 = y0.min(a.y.min(c.y)); + y1 = y1.max(a.y.max(c.y)); + } + let gap = gap.max((y1 - y0) / 400.0).max(1e-6); + let start = (y0 / gap).floor() * gap + gap * 0.5; + let mut xs: Vec = vec![]; + for i in 0..402u32 { + let y = start + f64::from(i) * gap; + if y.partial_cmp(&y1) != Some(std::cmp::Ordering::Less) { + break; + } + xs.clear(); + for (a, c) in &edges { + if (a.y <= y) != (c.y <= y) { + xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); + } + } + xs.sort_by(f64::total_cmp); + for pair in xs.as_chunks::<2>().0 { + out.move_to(unrot(Point::new(pair[0], y))); + out.line_to(unrot(Point::new(pair[1], y))); + } + } + out +} + +/// A path's elements with every coordinate as its bits, so NaN and -0.0 compare exactly. +fn path_bits(p: &BezPath) -> Vec<(u8, Vec)> { + let bits = |pts: &[Point]| pts.iter().flat_map(|p| [p.x.to_bits(), p.y.to_bits()]).collect(); + p.elements() + .iter() + .map(|el| match *el { + kurbo::PathEl::MoveTo(a) => (0, bits(&[a])), + kurbo::PathEl::LineTo(a) => (1, bits(&[a])), + kurbo::PathEl::QuadTo(a, b) => (2, bits(&[a, b])), + kurbo::PathEl::CurveTo(a, b, c) => (3, bits(&[a, b, c])), + kurbo::PathEl::ClosePath => (4, vec![]), + }) + .collect() +} + +/// A closed polygon through `pts`. +fn polygon(pts: impl IntoIterator) -> BezPath { + let mut bp = BezPath::new(); + for (i, p) in pts.into_iter().enumerate() { + if i == 0 { + bp.move_to(p); + } else { + bp.line_to(p); + } + } + bp.close_path(); + bp +} + +/// A polygon of `n` sides inscribed in the circle of radius `r` about the origin. +fn circle_polygon(n: u32, r: f64) -> BezPath { + polygon((0..n).map(|i| { + let t = std::f64::consts::TAU * f64::from(i) / f64::from(n); + Point::new(r * t.cos(), r * t.sin()) + })) +} + +/// The paths the hatch is checked on: many edges, a random star, holes, several subpaths, a +/// sliver, curves, edges along the hatch, repeated outlines, an open path, far coordinates, an +/// empty path and NaN and infinite coordinates. +fn hatch_cases() -> Vec<(&'static str, BezPath)> { + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + let mut rand = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + let star = polygon((0..300).map(|i| { + let t = std::f64::consts::TAU * f64::from(i) / 300.0; + let r = 100.0 + 300.0 * rand(); + Point::new(r * t.cos(), r * t.sin()) + })); + let mut holes = shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 200.0)).to_bezpath(); + holes.extend(polygon([(50.0, 50.0), (50.0, 150.0), (120.0, 150.0), (120.0, 50.0)].map(Point::from))); + holes.extend(polygon([(180.0, 40.0), (260.0, 100.0), (180.0, 160.0)].map(Point::from))); + holes.extend(circle_polygon(40, 30.0).iter().map(|el| match el { + kurbo::PathEl::MoveTo(p) => kurbo::PathEl::MoveTo(p + kurbo::Vec2::new(400.0, 100.0)), + kurbo::PathEl::LineTo(p) => kurbo::PathEl::LineTo(p + kurbo::Vec2::new(400.0, 100.0)), + other => other, + })); + let mut repeated = BezPath::new(); + for _ in 0..7 { + repeated.extend(shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)).to_bezpath()); + } + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((120.0, 10.0)); + open.line_to((60.0, 90.0)); + vec![ + ("2,000-sided circle", circle_polygon(2000, 500.0)), + ("300-point star", star), + ("holes and subpaths", holes), + ("sliver", polygon([(0.0, 0.0), (900.0, 1.0), (900.0, 1.002)].map(Point::from))), + ("curves", kurbo::Circle::new((10.0, -20.0), 300.0).to_path(0.01)), + ("edges along the hatch", polygon([(0.0, 0.0), (10.0, 10.0), (0.0, 20.0), (-10.0, 10.0)].map(Point::from))), + ("repeated outlines", repeated), + ("open path", open), + ("far from the origin", shapes::rectangle(Rect::new(0.0, 1e17, 64.0, 1e17 + 64.0)).to_bezpath()), + ("empty", BezPath::new()), + ("NaN", polygon([(0.0, 0.0), (100.0, f64::NAN), (100.0, 100.0), (0.0, 80.0)].map(Point::from))), + ("infinite", polygon([(0.0, 0.0), (f64::INFINITY, 50.0), (100.0, 100.0)].map(Point::from))), + ] +} + +#[test] +fn hatch_matches_testing_every_edge() { + for (name, bp) in hatch_cases() { + for gap in [0.5, 4.0, 40.0] { + assert_eq!(path_bits(&hatch(&bp, gap)), path_bits(&hatch_every_edge(&bp, gap)), "{name} at gap {gap}"); + } + } +} + +#[test] +fn hatch_tests_only_the_edges_spanning_each_line() { + let bp = circle_polygon(2000, 500.0); + let before = map::HATCH_EDGE_TESTS.with(std::cell::Cell::get); + let h = hatch(&bp, 4.0); + let tests = map::HATCH_EDGE_TESTS.with(std::cell::Cell::get) - before; + // Each line crosses the circle once, so it has one segment. + let lines = h.elements().len() / 2; + assert!(lines > 200, "{lines}"); + assert!(tests * 20 < lines * 2000, "{tests} edge tests on {lines} lines of 2,000 edges"); +} + +#[test] +fn hatch_sweep_finds_the_crossings_of_every_edge() { + let p = Point::new; + let edges = vec![ + (p(0.0, 0.0), p(1.0, 1.0)), + (p(1.0, 1.0), p(0.0, 2.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + (p(5.0, 1.0), p(9.0, 1.0)), + (p(2.0, -0.0), p(2.0, 0.0)), + (p(4.0, -0.0), p(4.0, 3.0)), + (p(6.0, 0.5), p(6.0, 0.5)), + (p(7.0, f64::NAN), p(7.0, 2.0)), + (p(8.0, 0.0), p(8.0, f64::INFINITY)), + (p(f64::NAN, 0.0), p(1.0, 2.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + ]; + let mut sweep = map::EdgeSweep::new(edges.clone()); + let mut xs = vec![]; + for y in [-2.0, -1.0, -0.0, 0.0, 0.5, 1.0, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0] { + let mut old: Vec = + edges.iter().filter(|(a, c)| (a.y <= y) != (c.y <= y)).map(|(a, c)| a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)).collect(); + xs.clear(); + sweep.crossings(y, &mut xs); + old.sort_by(f64::total_cmp); + xs.sort_by(f64::total_cmp); + let bits = |v: &[f64]| v.iter().map(|x| x.to_bits()).collect::>(); + assert_eq!(bits(&xs), bits(&old), "at y = {y}"); + } +} + +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn cpu_time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// Timings of 1,000 hatches by the sweep and by testing every edge, on a 2,000-sided circle of +/// radius 500 and on a 40-sided one, run in turn, 7 runs each. Ignored by default; it prints the +/// median, fastest and slowest run and sets no bound on them: +/// `cargo test --release -p vectorcraft-tools --lib hatch_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn hatch_perf() { + const RUNS: usize = 7; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + eprintln!("hatch_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + for (sides, r) in [(2000, 500.0), (2000, 100.0), (40, 100.0)] { + let bp = circle_polygon(sides, r); + assert_eq!(path_bits(&hatch(&bp, 4.0)), path_bits(&hatch_every_edge(&bp, 4.0))); + let (mut old, mut new) = (vec![], vec![]); + let every = || { + for _ in 0..1000 { + std::hint::black_box(hatch_every_edge(std::hint::black_box(&bp), 4.0)); + } + }; + let sweep = || { + for _ in 0..1000 { + std::hint::black_box(hatch(std::hint::black_box(&bp), 4.0)); + } + }; + for run in 0..RUNS { + // The two take turns going first. + if run % 2 == 0 { + old.push(cpu_time(every)); + new.push(cpu_time(sweep)); + } else { + new.push(cpu_time(sweep)); + old.push(cpu_time(every)); + } + } + old.sort(); + new.sort(); + eprintln!( + "hatch_perf: {sides:>5} sides r {r:>5}: every edge {:>9.3} ms ({:.3}-{:.3}), sweep {:>9.3} ms ({:.3}-{:.3})", + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } +} + /// An empty hidden sources group for a Live Paint group made in a test. fn empty_sources(d: &mut Document) -> Arc { let mut g = Node::group(d.alloc_id(), vec![]); diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 0f36a2e25f..3d33d93cbc 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -56,6 +56,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("rectangle", "Rectangle Tool", Some("M"), "tool-rect"), t("roundedRectangle", "Rounded Rectangle Tool", None, "tool-rounded-rect"), t("ellipse", "Ellipse Tool", Some("L"), "tool-ellipse"), + t(crate::circle::ID, "Circle Tool", None, "tool-circle"), t("polygon", "Polygon Tool", None, "tool-polygon"), t("star", "Star Tool", None, "tool-star"), t("flare", "Flare Tool", None, "tool-flare"), diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs new file mode 100644 index 0000000000..9e467b35d6 --- /dev/null +++ b/crates/tools/src/circle.rs @@ -0,0 +1,309 @@ +//! The Circle tool draws a circle through points it is given (`shape.circleThroughPoints`). +//! +//! Two points are the ends of a diameter: a drag from one to the other, or a click on each. A click +//! on a first point, then a press on a second point dragged to a third, draws the circle through +//! the three. Shift keeps the second point at 45° steps from the first (from General › Constrain +//! Angle), Alt rounds the diameter of a circle drawn on two points to the nearest tick of the +//! rulers at the current zoom, in the General unit, and every point snaps to Smart Guides. Until +//! the release, the tool shows the circle as a dashed outline (solid once it is more than 50,000 +//! screen points around) with its points, its center as a small cross, a line from the center to +//! each point and, with Measurement Labels on, the diameter by the pointer. The circle is one undo +//! step. Escape, a press dropped part way, and an edit, Undo or Redo made outside the tool drop +//! the first point. A second press within 3 screen points +//! of the first point, or one that snaps to it, is a press on it: let go there (a double-click) it +//! places nothing, and dragged out it draws the circle on the diameter it drags out. Where no +//! circle passes through the points (two are the same, three lie on one line) or the circle would +//! reach past the canvas, the tool shows none and the release draws nothing; for three different +//! points on one line, or a circle past the canvas, the pointer shows "Circle too large". + +use serde_json::{Value, json}; +use vectorcraft_doc::MAX_COORD; +use vectorcraft_geom::{Point, Rect, Vec2, shapes}; + +use crate::guides::{DrawSnap, Leave}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "circle"; + +/// How far (screen points) the pointer travels from a press before the press counts as a drag. +const DRAG_PX: f64 = 2.0; +/// Half the length (screen points) of each arm of the cross at the circle's center. +const CROSS_PX: f64 = 4.0; +/// How near (screen points) the first point a second click counts as a click on it. +const REACH_PX: f64 = 3.0; +/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. +const DASHED_PX: f64 = 50_000.0; + +/// The press in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Press { + /// The first point `at`, pressed with the pointer at `from` (before snapping): a release after + /// a drag draws the circle on that diameter. + First { at: Point, from: Point, dragged: bool }, + /// The second press, after a click placed the first point, with the pointer at `from` (before + /// snapping). `snapped` is the point it snapped to, and `at` that point with Alt's rounding of + /// the diameter. A release without a drag draws the circle on the diameter to `at`; a drag + /// places the third point and the circle passes through `snapped`. A press within + /// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let + /// go there it places nothing, and dragged out it draws the circle on the diameter it drags out. + Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool }, +} + +#[derive(Default)] +pub struct CircleTool { + snap: DrawSnap, + /// The first point, placed by a click (or by the press of a drag in progress). + first: Option, + press: Option, + /// Where the pointer is, snapped: the point the next press or release places. + pointer: Option, +} + +/// The command the tool runs for `points`. +fn command(points: &[Point]) -> (String, Value) { + let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); + ("shape.circleThroughPoints".into(), json!({ "points": pairs })) +} + +/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` +/// draws it: none where no circle passes through them or it would reach past the canvas. +pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { + let on_canvas = |(c, r): &(Point, f64)| [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD); + shapes::circle_through_points(points).filter(on_canvas) +} + +/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on +/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and +/// when that rounding leaves no distance. +fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { + let d = first.distance(p); + let rounded = cx.unit.snap_to_ruler_tick(d, cx.zoom); + if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p } +} + +/// Are the points two or more different points through which no circle is drawn: three on one +/// line, or a circle that would reach past the canvas? +fn too_large(points: &[Point]) -> bool { + let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); + points.len() >= 2 && distinct && circle_of(points).is_none() +} + +impl CircleTool { + fn clear(&mut self) { + self.first = None; + self.press = None; + self.pointer = None; + self.snap.clear(); + } + + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. + fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { + self.first.map(|a| Leave::segment(cx, a, mods.shift)) + } + + /// The points the circle passes through as the tool shows it now. + fn points(&self) -> Vec { + let mut out: Vec = self.first.into_iter().collect(); + match self.press { + Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), + // A press on the first point adds no point: a drag from it drags out a diameter. + Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), + Some(Press::Second { at, dragged: false, .. }) => out.push(at), + Some(Press::Second { snapped, dragged: true, .. }) => { + out.push(snapped); + out.extend(self.pointer); + } + } + out + } + + /// The second point as the tool shows it: none for a press on the first point. + fn second(&self) -> Option { + match self.press { + Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), + Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), + _ => None, + } + } + + /// Runs the circle through `points` and starts afresh; where no circle is drawn through them + /// (the tool showed none), it only starts afresh. + fn draw(&mut self, points: &[Point]) -> Vec { + self.clear(); + if circle_of(points).is_none() { + return vec![]; + } + let (c, v) = command(points); + vec![Action::Exec(c, v)] + } + + /// Is the press a drag at `ev`: dragged already, or `ev` is [`DRAG_PX`] or more from the press? + fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool { + match self.press { + Some(Press::First { from, dragged, .. } | Press::Second { from, dragged, .. }) => dragged || ev.pos.distance(from) >= cx.tol(DRAG_PX), + None => false, + } + } +} + +impl Tool for CircleTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + // A drag ends where it is let go: the release moves the points as a drag to it would. A + // click, or a release within DRAG_PX of the press, keeps the points of the press. + if ev.kind == PointerKind::Up && self.drags(cx, ev) { + self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, ..*ev }); + } + match ev.kind { + PointerKind::Move => { + let leave = self.leave(cx, ev.mods); + let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + vec![] + } + PointerKind::Down => { + match self.first { + None => { + let at = self.snap.press(cx, ev.pos, &[], None); + self.first = Some(at); + self.press = Some(Press::First { at, from: ev.pos, dragged: false }); + self.pointer = Some(at); + } + Some(a) => { + let leave = self.leave(cx, ev.mods); + let snapped = self.snap.press(cx, ev.pos, &[], leave.as_ref()); + let at = round_diameter(cx, a, snapped, ev.mods); + let on_first = snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX); + self.press = Some(Press::Second { at, snapped, from: ev.pos, on_first, dragged: false }); + self.pointer = Some(at); + } + } + vec![] + } + PointerKind::Drag => { + match &mut self.press { + Some(Press::First { at, from, dragged }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = Leave::segment(cx, *at, ev.mods.shift); + self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods)); + } + // Dragged from the first point, the pointer is the other end of a diameter, as + // for a drag from a first press. + Some(Press::Second { from, on_first: true, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = self.first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + let p = self.snap.drag(cx, ev.pos, leave.as_ref()); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + } + Some(Press::Second { from, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + self.pointer = Some(self.snap.drag(cx, ev.pos, None)); + } + None => {} + } + vec![] + } + PointerKind::Up => match (self.press.take(), self.first, self.pointer) { + (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), + // A click places the first point; the guides of the press go. + (Some(Press::First { .. }), ..) => { + self.snap.clear(); + vec![] + } + // The second click of a double-click lands on the first point and places nothing; + // a drag from there draws the circle on the diameter it drags out. + (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], + (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), + (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), + // Three points: Alt's rounding of the diameter does not apply. + (Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]), + _ => vec![], + }, + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape { + self.clear(); + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.first.is_some() + } + + /// A first point placed: Escape drops it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.first.is_some() + } + + fn busy(&self) -> bool { + self.first.is_some() + } + + /// A dropped press (a second finger, a canceled touch) drops the points placed so far. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.pointer = None; + self.snap.clear(); + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops the first point. + fn history_moved(&mut self) { + self.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + let points = self.points(); + let color = crate::draw2::FEEDBACK; + if let Some((c, r)) = circle_of(&points) { + let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + // The canvas draws a dashed outline dash by dash along its whole length: a circle longer + // than DASHED_PX on screen is drawn solid instead. + let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); + o.push(Overlay::Path { path, color, width: 1.0, dashed }); + for p in &points { + o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); + } + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); + if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { + o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); + } + } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + o.push(Overlay::Label { p, text: "Circle too large".into(), color }); + } + for p in self.first.into_iter().chain(self.second()) { + o.push(Overlay::Anchor { p, color, filled: true, size: 6.0 }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs new file mode 100644 index 0000000000..e262d242ef --- /dev/null +++ b/crates/tools/src/circle/tests.rs @@ -0,0 +1,352 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::Selection; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +fn click(t: &mut CircleTool, cx: &ToolContext, p: (f64, f64)) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, p, Mods::default())); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, Mods::default()))); + acts +} + +/// A press at `from`, dragged through `path` and let go at its last point. +fn drag(t: &mut CircleTool, cx: &ToolContext, from: (f64, f64), path: &[(f64, f64)], mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, from, mods)); + for p in path { + acts.extend(t.pointer(cx, &ev(PointerKind::Drag, *p, mods))); + } + let end = path.last().copied().unwrap_or(from); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, end, mods))); + acts +} + +fn circle(points: &[(f64, f64)]) -> Vec { + let pairs: Vec = points.iter().map(|(x, y)| json!([x, y])).collect(); + vec![Action::Exec("shape.circleThroughPoints".into(), json!({ "points": pairs }))] +} + +/// The dashed circle the tool shows: its bounding box. +fn preview(o: &[Overlay]) -> Option { + o.iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-9) +} + +/// A drag from one point to another draws the circle with those two as the ends of a diameter. +#[test] +fn a_drag_draws_the_circle_on_its_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 330.0), (380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); +} + +/// A click places the first point and a second click the other end of the diameter. In between, +/// the tool shows the circle through the first point and the pointer, its center cross, its radii +/// and its diameter. +#[test] +fn two_clicks_draw_the_circle_on_their_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert!(t.ends_on_escape(&cx) && t.claims_key(&cx, ToolKey::Escape)); + t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default())); + let o = t.overlays(&cx); + // Center (340, 330), radius 50. + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + let center = Point::new(340.0, 330.0); + let lines = o.iter().filter(|o| matches!(o, Overlay::Line { a, .. } if *a == center)).count(); + assert_eq!(lines, 2, "a radius to each point: {o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 100"))), "{o:?}"); + let without_labels = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&without_labels).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert!(!t.ends_on_escape(&cx)); +} + +/// A click, then a press on a second point dragged to a third, draws the circle through the three. +#[test] +fn a_click_and_a_drag_draw_the_circle_through_three_points() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 360.0), Mods::default())); + // (300, 300), (380, 300) and (300, 360): the right angle stands on the diameter, center + // (340, 330), radius 50. + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); +} + +/// A drag ends where it is let go, also when the release is away from the last drag: from a first +/// press, from a second press, and from a press on the first point. A release within 2 screen +/// points of a second press is still a click and keeps the point of the press. +#[test] +fn a_drag_ends_where_it_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.pointer(&cx, &ev(down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (300.0, 340.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (300.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (380.0, 360.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (381.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 360.0)])); +} + +/// Three points on one line show no circle, and the release draws nothing and starts afresh. A +/// circle past the canvas is not shown either. +#[test] +fn points_on_one_line_show_no_circle() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (200.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 300.0), Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 300.0), Mods::default())), vec![]); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + assert_eq!(circle_of(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)]), None); + assert_eq!(circle_of(&[Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(100.0, 0.001)]), None); +} + +/// Shift keeps the second point at 45° steps from the first. +#[test] +fn shift_keeps_the_diameter_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = CircleTool::default(); + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(400.0, 310.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + let end = &v["points"][1]; + assert!((end[1].as_f64().unwrap() - 300.0).abs() < 1e-9, "level with the first point: {v}"); +} + +/// Alt rounds the diameter to the nearest ruler tick at the current zoom: every 5 pt at 100% and +/// every 2.5 pt at 200% in points, keeping the direction from the first point; for a drag, for a +/// second click and in the preview. +#[test] +fn alt_rounds_the_diameter_to_ruler_ticks() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + // The second point of the one circle `acts` draws. + let second = |acts: Vec| { + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + Point::new(v["points"][1][0].as_f64().unwrap(), v["points"][1][1].as_f64().unwrap()) + }; + let mut t = CircleTool::default(); + let end = second(drag(&mut t, &cx, (300.0, 300.0), &[(373.0, 300.0)], alt)); + assert!(end.distance(Point::new(375.0, 300.0)) < 1e-9, "{end:?}"); + // (31.2, 41.6) is 52 from the origin, and Alt makes it 50: (30, 40). + click(&mut t, &cx, (0.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Move, (31.2, 41.6), alt)); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(-10.0, -5.0, 40.0, 45.0)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, (31.2, 41.6), alt)), vec![]); + let end = second(t.pointer(&cx, &ev(PointerKind::Up, (31.2, 41.6), alt))); + assert!(end.distance(Point::new(30.0, 40.0)) < 1e-9, "{end:?}"); + let zoomed = ToolContext { zoom: 2.0, ..cx }; + for (to, want) in [(51.0, 50.0), (51.5, 52.5)] { + let end = second(drag(&mut t, &zoomed, (0.0, 0.0), &[(0.0, to)], alt)); + assert!(end.distance(Point::new(0.0, want)) < 1e-9, "{to}: {end:?}"); + } + // Without Alt the pointer is used as it is. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(373.0, 300.0)], Mods::default()), circle(&[(300.0, 300.0), (373.0, 300.0)])); +} + +/// Alt rounds only a diameter: a second press dragged to a third point keeps the second point +/// where it was pressed, and a second press 2.6 pt from the first point, which Alt's rounding +/// would move to 5 pt, is still a press on the first point and places nothing. +#[test] +fn alt_leaves_three_points_and_presses_on_the_first_point_alone() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (0.0, 0.0)); + assert_eq!(drag(&mut t, &cx, (31.2, 41.6), &[(45.0, 20.0), (60.0, 0.0)], alt), circle(&[(0.0, 0.0), (31.2, 41.6), (60.0, 0.0)])); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, (302.6, 300.0), alt)), vec![]); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (302.6, 300.0), alt)), vec![]); + assert!(t.ends_on_escape(&cx), "the first point stays"); +} + +/// Three different points on one line show "Circle too large" by the pointer instead of a circle; +/// a pointer back on the first point does not. +#[test] +fn points_on_one_line_say_the_circle_is_too_large() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let label = |t: &CircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Label { p, text, .. } => Some((*p, text.clone())), + _ => None, + }) + }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (200.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 300.0), Mods::default())); + assert_eq!(label(&t), Some((Point::new(300.0, 300.0), "Circle too large".to_string()))); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 290.0), Mods::default())); + assert_eq!(label(&t), None, "a circle is shown"); + t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); + assert_eq!(label(&t), None, "the third point is on the second"); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); + assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); +} + +/// Escape drops the first point; so do a dropped press and an edit made outside the tool. A +/// second click on the first point places nothing. +#[test] +fn escape_and_outside_edits_drop_the_first_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(click(&mut t, &cx, (300.5, 300.0)), vec![], "a double-click places one point"); + assert!(t.ends_on_escape(&cx)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + click(&mut t, &cx, (300.0, 300.0)); + t.history_moved(); + assert!(!t.ends_on_escape(&cx)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.drop_press(&cx); + assert!(!t.ends_on_escape(&cx)); + // After all of that, two clicks start a new circle. + click(&mut t, &cx, (10.0, 10.0)); + assert_eq!(click(&mut t, &cx, (30.0, 10.0)), circle(&[(10.0, 10.0), (30.0, 10.0)])); +} + +/// The points snap to Smart Guides: a press near the rectangle's corner anchor at (100, 100) places +/// the point on it. +#[test] +fn points_snap_to_smart_guides() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (101.0, 101.5), Mods::default())); + click(&mut t, &cx, (101.0, 101.5)); + assert_eq!(click(&mut t, &cx, (300.0, 100.0)), circle(&[(100.0, 100.0), (300.0, 100.0)])); +} + +/// A click is measured from where the pointer was pressed, not from the point it snapped to: a +/// second press pulled 1.8 pt onto the corner anchor at (100, 100) and moved 0.5 pt before the +/// release still draws the circle on that diameter. +#[test] +fn a_snapped_second_click_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (101.5, 101.5), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.5, 101.5), Mods::default())), circle(&[(300.0, 100.0), (100.0, 100.0)])); +} + +/// A second press within 3 screen points of the first point is a press on it: dragged out, it +/// draws the circle on the diameter it drags out, whether it landed on the first point or next to +/// it; a press farther away and dragged places the second and third points. +#[test] +fn a_drag_from_the_first_point_draws_the_circle_on_its_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + let acts = drag(&mut t, &cx, (301.0, 300.0), &[(300.0, 350.0), (300.0, 400.0)], Mods::default()); + assert_eq!(acts, circle(&[(300.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + let acts = drag(&mut t, &cx, (304.0, 300.0), &[(300.0, 350.0), (300.0, 400.0)], Mods::default()); + assert_eq!(acts, circle(&[(300.0, 300.0), (304.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 400.0), Mods::default())); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(250.0, 300.0, 350.0, 400.0)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (300.0, 400.0)])); +} + +/// A second press farther than 3 screen points from the first point that snaps to it is a press on +/// it too: the first point is the rectangle's corner anchor at (100, 100), and a press 3.2 pt away +/// snaps back to that anchor. +#[test] +fn a_second_press_that_snaps_to_the_first_point_is_a_press_on_it() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (103.2, 100.0), Mods::default())); + assert_eq!(t.second(), None, "the press snapped to the first point: {:?}", t.press); + t.pointer(&cx, &ev(PointerKind::Drag, (100.0, 150.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (100.0, 150.0), Mods::default())), circle(&[(100.0, 100.0), (100.0, 150.0)])); +} + +/// A circle more than 50,000 screen points around is previewed solid, not dashed: three points +/// nearly on one line give a radius of about 1,250,000 pt. +#[test] +fn a_huge_circle_is_previewed_solid() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (0.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Down, (1000.0, 0.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (500.0, 0.1), Mods::default())); + let o = t.overlays(&cx); + assert_eq!(preview(&o), None, "{o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { dashed: false, .. })), "{o:?}"); + // At 100% a circle 100 pt across is dashed. + t.pointer(&cx, &ev(PointerKind::Drag, (500.0, 300.0), Mods::default())); + assert!(preview(&t.overlays(&cx)).is_some()); +} + +/// The tool is in the Ellipse tool's group, after the Ellipse tool. +#[test] +fn the_circle_tool_follows_the_ellipse_tool() { + let tool = crate::create(ID); + assert_eq!(tool.id(), ID); + let group = crate::catalog::group_of(ID).unwrap(); + assert_eq!(crate::catalog::group_of("ellipse"), Some(group)); + let ids: Vec<&str> = crate::TOOL_GROUPS[group].iter().map(|t| t.id).collect(); + let ellipse = ids.iter().position(|id| *id == "ellipse").unwrap(); + assert_eq!(ids.get(ellipse + 1), Some(&ID)); +} diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 13691da613..2e23159e5c 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -419,6 +419,24 @@ impl Tool for CropImageTool { }; } + /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. `ppi`, + /// `reference` and `linked` take the values [`check_options`] takes (the selected image's + /// limit on `ppi` is checked by `tool.setOption`, which knows the selection). + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if matches!(key, "ppi" | "reference" | "linked") { + return check_options(&serde_json::Map::from_iter([(key.to_string(), value.clone())]), None); + } + if key != "rect" { + return Err(crate::option_check::unknown(key)); + } + let numbers = value.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(Value::as_f64).collect::>>()); + match numbers.as_deref() { + _ if value.is_null() => Ok(()), + Some([x, y, w, h]) if [x, y, w, h].iter().all(|n| n.is_finite()) && *w >= 0.0 && *h >= 0.0 => Ok(()), + _ => Err(format!("`{key}` must be [x, y, width, height]: four finite numbers, width and height not negative")), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.reset(); vec![] @@ -635,6 +653,15 @@ mod tests { ] { assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}"); } + // The tool takes the same values on its own, without an image's limit. + let t = CropImageTool::default(); + for (k, v) in [("ppi", json!(72)), ("ppi", json!(null)), ("reference", json!(0)), ("linked", json!(true)), ("rect", json!(null))] { + assert_eq!(t.check_option(k, &v), Ok(()), "{k}: {v}"); + } + assert_eq!(t.check_option("reference", &json!(9)), Err("`reference` must be a whole number from 0 to 8, not 9".into())); + assert_eq!(t.check_option("linked", &json!(1)), Err("`linked` must be true or false, not 1".into())); + assert_eq!(t.check_option("ppi", &json!(2401)), Err("`ppi` must be a number from 1 to 2400 or null, not 2401".into())); + assert_eq!(t.check_option("size", &json!(1)), Err("unknown option `size`".into())); } /// An image's own resolution, and the most it can be cropped to. diff --git a/crates/tools/src/cut.rs b/crates/tools/src/cut.rs index 906a632fb3..514e41e4c0 100644 --- a/crates/tools/src/cut.rs +++ b/crates/tools/src/cut.rs @@ -214,6 +214,15 @@ impl Tool for CutTool { _ => {} } } + /// Mirror & Cut's `axis` and `keep`; the other cutting tools have no options. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match (self.id, key) { + ("mirrorCut", "axis") => c::one_of(key, v, &["vertical", "horizontal", "free"]), + ("mirrorCut", "keep") => c::one_of(key, v, &["left", "right", "top", "bottom"]), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index d78850e78e..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,28 @@ 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)>, + /// While a dimension is placed: the lines of the visible, unlocked linear dimensions in the + /// document before its first preview ([`dimension_lines`]), which its line can line up with. + levels: Vec, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -170,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() { @@ -191,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 @@ -285,6 +466,58 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false))) } +/// The line of a linear dimension already drawn: its ends and its direction. +type DimensionLine = ((Point, Point), Vec2); + +/// The lines of the visible, unlocked linear dimensions in the document. Bounded work, as in +/// [`on_dimensions`]. +fn dimension_lines(cx: &ToolContext) -> Vec { + fn visit(n: &Node, budget: &mut usize, out: &mut Vec) { + if *budget == 0 || !n.visible || n.locked { + return; + } + *budget -= 1; + if let Some(d) = &n.extras().dimension { + if d.mode == DimensionMode::Linear { + out.push((d.line_ends(), d.direction())); + } + return; + } + for c in n.children().into_iter().flatten().rev() { + visit(c, budget, out); + } + } + let (mut budget, mut out) = (20_000usize, vec![]); + for n in cx.doc.layers.iter().rev() { + visit(n, &mut budget, &mut out); + } + out +} + +/// Where the line of the linear dimension `d`, placed through `p`, lands on the level of one of +/// the `levels` that runs parallel to it, within `reach` of `p` across the line: the point to +/// place `d` through, and the ends of that other line. The nearest level wins, then the line +/// nearest `p` along it (none nearer than a line that `p` lies across). +fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> Option<(Point, (Point, Point))> { + if d.mode != DimensionMode::Linear { + return None; + } + let (u, normal) = (d.direction(), d.normal()); + let mut best: Option<(f64, f64, f64, (Point, Point))> = None; + for &(ends, direction) in levels { + if u.cross(direction).abs() > 1e-6 { + continue; + } + let shift = (ends.0 - p).dot(normal); + let (s0, s1) = ((ends.0 - p).dot(u), (ends.1 - p).dot(u)); + let along = if s0 * s1 <= 0.0 { 0.0 } else { s0.abs().min(s1.abs()) }; + if shift.is_finite() && along.is_finite() && shift.abs() <= reach && best.is_none_or(|(s, a, _, _)| (shift.abs(), along) < (s, a)) { + best = Some((shift.abs(), along, shift, ends)); + } + } + best.map(|(_, _, shift, ends)| (p + normal * shift, ends)) +} + /// The point of `edge` closest to `p`. fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { use vectorcraft_geom::kurbo::ParamCurveNearest; @@ -303,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; @@ -324,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 @@ -341,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)); } @@ -435,6 +695,7 @@ impl DimensionTool { p } fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec { + self.level_guide = None; let Some(d) = &mut self.pending else { return vec![] }; if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) && let Some(Target::Radial { center, radius, .. }) = self.press.as_ref().and_then(|(_, t)| t.as_ref()) @@ -462,10 +723,18 @@ impl DimensionTool { if d.resolve(cx.doc).is_err() { return vec![]; } - d.place(p); + // With Smart Guides on, a linear dimension's line lands on the level of a parallel + // dimension line already drawn within the Smart Guides snapping tolerance. The lines are + // read before the first preview, so the preview of this dimension is not one of them. + if !self.began { + self.levels = dimension_lines(cx); + } + let level = if cx.smart_guides { line_level(&self.levels, d, p, cx.snap_tol()) } else { None }; + d.place(level.map_or(p, |(on_level, _)| on_level)); if d.validate().is_err() { return vec![]; } + self.level_guide = level.map(|(_, ends)| ends); let mut actions = vec![]; if !self.began { actions.push(Action::Begin("Create Dimension".into())); @@ -488,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; @@ -495,21 +766,30 @@ impl DimensionTool { self.snap.clear(); self.snapped = None; self.second = None; + self.level_guide = None; + self.levels.clear(); } /// A plain click: picks a point or a line, or measures a circle's radius. fn click(&mut self, cx: &ToolContext, p: Point, target: Option, mods: Mods) -> Vec { 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)); @@ -579,6 +859,13 @@ impl Tool for DimensionTool { self.style = o; } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "mode" => crate::option_check::one_of(key, value, &["linear", "angular", "radial", "radius", "diameter"]), + "style" => DimensionOptions::from_params(value.clone()).map(|_| ()), + _ => Err(crate::option_check::unknown(key)), + } + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.at = ev.pos; self.shift = ev.mods.shift; @@ -602,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![] } @@ -657,6 +947,7 @@ impl Tool for DimensionTool { self.press = None; if self.pending.is_some() && self.began { self.began = false; + self.level_guide = None; vec![Action::Cancel] } else { vec![] @@ -720,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 } }); @@ -734,6 +1025,21 @@ impl Tool for DimensionTool { if linear_pick { out.extend(self.snap.guides().iter().cloned()); } + // A dimension line placed on the level of another: one alignment guide across both lines, + // unless Alignment Guides are off. + if cx.alignment_guides + && let (Some(d), Some((c, e))) = (&self.pending, self.level_guide) + { + let (a, b) = d.line_ends(); + let u = d.direction(); + let along = |q: &Point| q.to_vec2().dot(u); + let ends = [a, b, c, e]; + if let (Some(lo), Some(hi)) = + (ends.iter().min_by(|p, q| along(p).total_cmp(&along(q))), ends.iter().max_by(|p, q| along(p).total_cmp(&along(q)))) + { + out.push(Overlay::Line { a: *lo, b: *hi, color: cx.smart_guide_color, dashed: false }); + } + } out } } @@ -771,6 +1077,21 @@ mod tests { assert!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 60.0)).is_empty(), "the release places nothing"); } + /// Of two dimension lines on one level, a line the pointer lies across wins over a line whose + /// end is nearer the pointer. + #[test] + fn a_line_the_pointer_lies_across_wins_on_one_level() { + let pt = Point::new; + let d = DimensionTool::default().recipe(DimensionMode::Linear, pt(200.0, 200.0), pt(300.0, 200.0), pt(250.0, 200.0), None); + let across = ((pt(0.0, 170.0), pt(400.0, 170.0)), Vec2::new(1.0, 0.0)); + let beside = ((pt(100.0, 170.0), pt(200.0, 170.0)), Vec2::new(1.0, 0.0)); + for levels in [[beside, across], [across, beside]] { + let (at, ends) = line_level(&levels, &d, pt(250.0, 172.0), 4.0).expect("on the level"); + assert!(at.distance(pt(250.0, 170.0)) < 1e-9, "{at:?}"); + assert_eq!(ends, across.0); + } + } + #[test] fn a_dropped_placement_press_does_not_commit_the_dimension() { let (d, _) = doc_with_rect(); @@ -930,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/direct.rs b/crates/tools/src/direct.rs index 6586cb8586..9323bfb20f 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -384,6 +384,18 @@ pub(crate) fn spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { v } +/// [`spines`] of the blends that are themselves selected, topmost first. When no selected object +/// is a blend, it returns an empty list without walking the document or building any spine. +pub(crate) fn selected_spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { + let is_blend = |id: &NodeId| cx.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. })); + if !cx.selection.objects.iter().any(is_blend) { + return vec![]; + } + let mut v = spines(cx); + v.retain(|(id, _)| cx.selection.contains(*id)); + v +} + /// The spine point under `p`: (blend, anchor, where it is). fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, Point)> { spines(cx).into_iter().find_map(|(id, path)| { @@ -395,7 +407,7 @@ fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usiz /// The segment of a selected blend's spine passing within `tol` of `p`: (blend, segment, t, whether /// it is straight). pub(crate) fn hit_spine_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { - spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| { + selected_spines(cx).into_iter().find_map(|(id, path)| { let (si, seg, t, _, dist) = path.nearest(p)?; (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) }) @@ -1348,7 +1360,7 @@ impl DirectSelectionTool { if hit.as_ref().and_then(|h| cx.doc.node(h.leaf)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { return vec![Action::SwitchTool("type".into())]; } - // Outside the isolated art it leaves isolation mode, as with the Selection tool (#4466). + // Outside the isolated art it runs Exit Isolation Mode, as with the Selection tool (#4466). if hit.is_none() && cx.isolation.is_some() { return vec![Action::Exec("object.exitIsolation".into(), json!({}))]; } @@ -1662,7 +1674,7 @@ impl DirectSelectionTool { // marquee or an Alt-marquee, every object it touches, each whole (#8047). if enclosed || whole || self.group { (self.spine, self.spine_more) = (None, vec![]); - let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); + let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline, !cx.guides); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched }; @@ -1672,8 +1684,11 @@ impl DirectSelectionTool { } // Anchors inside the rect, on editable paths inside isolation mode. let mut sel: Vec<(NodeId, Vec)> = vec![]; + // Guide paths only while guides can be picked: not while they are locked or hidden (#8538). walk_pickable(cx.doc, cx.isolation, |n| { - if let NodeKind::Path { path, .. } = &n.kind { + if let NodeKind::Path { path, guide, .. } = &n.kind + && (cx.guides || !*guide) + { let v: Vec = path.anchors().filter(|(_, _, a)| r.contains(a.p)).map(|(s, i, _)| (s, i)).collect(); if !v.is_empty() { sel.push((n.id, v)); @@ -1722,7 +1737,7 @@ impl DirectSelectionTool { // marquee that holds none of them drops the points picked before. let mut spined: Option = None; if !self.group { - let found = spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| { + let found = selected_spines(cx).into_iter().find_map(|(id, path)| { let inside: BTreeSet = path.anchors().filter(|(s, _, a)| *s == 0 && r.contains(a.p)).map(|(_, i, _)| i).collect(); (!inside.is_empty()).then_some((id, inside)) }); @@ -1761,7 +1776,7 @@ impl DirectSelectionTool { } // Objects without anchors to pick (type, images, symbols…) are selected whole when // the marquee touches them, as with the Selection tool (#927). - for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) { + for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline, !cx.guides) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) && spined != Some(id) { sel.push((id, vec![])); @@ -1773,7 +1788,8 @@ impl DirectSelectionTool { let mut crossed: Vec<(NodeId, Vec)> = vec![]; if !self.group { walk_pickable(cx.doc, cx.isolation, |n| { - if let NodeKind::Path { path, .. } = &n.kind + if let NodeKind::Path { path, guide, .. } = &n.kind + && (cx.guides || !*guide) && editable(n.id) { let segs = crossed_segments(path, r); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a0fabb9cb8..4f3b795921 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -416,6 +416,141 @@ fn spine_segments_bend_with_the_anchor_point_tool_and_direct_selection() { assert_eq!(t.pointer(&curved, &PointerEvent::new(PointerKind::Up, 160.0, 345.0)), vec![Action::Commit]); } +/// [`selected_spines`] written as a filter of every spine, for comparing results. +fn every_spine_then_selected(cx: &ToolContext) -> Vec<(NodeId, PathData)> { + spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).collect() +} + +/// [`hit_spine_segment`] written over [`every_spine_then_selected`], for comparing results. +fn hit_spine_segment_of_every_spine(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { + every_spine_then_selected(cx).into_iter().find_map(|(id, path)| { + let (si, seg, t, _, dist) = path.nearest(p)?; + (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) + }) +} + +/// [`blend_doc`] with a stored spine the keys are spread along (not pinned to anchors), whose +/// layout builds a [`vectorcraft_doc::blend::Spine`], and the id of the plain rectangle beside it. +fn blend_doc_with_spread_spine() -> (vectorcraft_doc::Document, NodeId, NodeId, NodeId) { + let (mut d, g, k1) = blend_doc(); + let Some(rect) = d.layers[0].children().into_iter().flatten().map(|n| n.id).find(|id| *id != g) else { panic!("rectangle") }; + let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(110.0, 310.0), Point::new(210.0, 310.0)], false); + sp.bend_segment(0, 0.5, vectorcraft_geom::Vec2::new(0.0, 20.0)); + let Some(NodeKind::Blend { spec, .. }) = d.node_mut(g).map(|n| &mut n.kind) else { panic!("blend") }; + (spec.spine, spec.key_anchors) = (Some(PathData::single(sp)), vec![]); + (d, g, k1, rect) +} + +/// With no blend among the selected objects, the selected-spine check builds no blend spine; with +/// the blend selected it still finds the spine. +#[test] +fn the_selected_spine_check_builds_no_spine_without_a_selected_blend() { + let (d, g, _, rect) = blend_doc_with_spread_spine(); + let p = paint(); + let mut s = Selection::default(); + s.set([rect]); + let c = cx(&d, &s, &p); + let before = vectorcraft_doc::blend::spines_built(); + assert_eq!(hit_spine_segment(&c, Point::new(160.0, 330.0), 4.0), None); + assert!(selected_spines(&c).is_empty()); + assert_eq!(vectorcraft_doc::blend::spines_built() - before, 0, "no spine built"); + s.set([rect, g]); + let c = cx(&d, &s, &p); + assert!(hit_spine_segment(&c, Point::new(160.0, 330.0), 4.0).is_some_and(|h| h.0 == g)); +} + +/// The selected-spine check gives what a filter of every spine gives, for selections with and +/// without the blend, its key, a stale id, and the blend locked, hidden or without a spine. +#[test] +fn the_selected_spine_check_matches_a_filter_of_every_spine() { + let (d, g, k1, rect) = blend_doc_with_spread_spine(); + let p = paint(); + let mut docs = vec![d.clone()]; + for change in 0..3 { + let mut d = d.clone(); + if let Some(n) = d.node_mut(g) { + match change { + 0 => n.locked = true, + 1 => n.visible = false, + _ => { + if let NodeKind::Blend { spec, .. } = &mut n.kind { + spec.no_spine = true; + } + } + } + } + docs.push(d); + } + let selections: [&[NodeId]; 7] = [&[], &[rect], &[g], &[rect, g], &[g, rect], &[k1], &[NodeId(9_999)]]; + for (di, d) in docs.iter().enumerate() { + for ids in selections { + let mut s = Selection::default(); + s.set(ids.iter().copied()); + let c = cx(d, &s, &p); + assert_eq!(selected_spines(&c), every_spine_then_selected(&c), "doc {di}, {ids:?}"); + for x in (90..=230).step_by(5) { + for y in (295..=340).step_by(5) { + let at = Point::new(f64::from(x), f64::from(y)); + assert_eq!(hit_spine_segment(&c, at, 4.0), hit_spine_segment_of_every_spine(&c, at, 4.0), "doc {di}, {ids:?}, {at:?}"); + } + } + } + } +} + +/// Times the selected-spine check on 20,000 paths and 200 blends with curved spines, against the +/// same check written as a filter of every spine, in one process: 500 points, the median of 7 +/// runs. Case A selects one plain path, case B one blend. +#[test] +#[ignore = "manual large-document timing"] +fn selected_spine_check_timing() { + let mut d = vectorcraft_doc::Document::new(4000.0, 4000.0); + let l = d.layers[0].id; + for i in 0..20_000_u32 { + let (x, y) = (f64::from(i % 200) * 20.0, f64::from(i / 200) * 20.0); + let id = d.alloc_id(); + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + d.insert(Some(l), 0, vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + let first_path = d.layers[0].children().into_iter().flatten().map(|n| n.id).next(); + let mut blends = vec![]; + for i in 0..200_u32 { + let (x, y) = (f64::from(i % 20) * 200.0, 2050.0 + f64::from(i / 20) * 190.0); + let key = |id: NodeId, x: f64| { + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)); + std::sync::Arc::new(vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())) + }; + let (g, k1, k2) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(x + 10.0, y + 10.0), Point::new(x + 110.0, y + 10.0)], false); + sp.bend_segment(0, 0.5, vectorcraft_geom::Vec2::new(0.0, 20.0)); + let spec = vectorcraft_doc::BlendSpec { spine: Some(PathData::single(sp)), ..Default::default() }; + let b = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, x), key(k2, x + 100.0)], spec: Box::new(spec) }); + d.insert(Some(l), 0, b).unwrap(); + blends.push(g); + } + let points: Vec = (0..500_u32).map(|i| Point::new(f64::from(i * 37 % 4000), f64::from(i * 53 % 4000))).collect(); + let p = paint(); + let (Some(plain), Some(&blend)) = (first_path, blends.first()) else { panic!("fixture") }; + for (case, id) in [("A: one plain path selected", plain), ("B: one blend selected", blend)] { + let mut s = Selection::default(); + s.set([id]); + let c = cx(&d, &s, &p); + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + let t = std::time::Instant::now(); + let a: Vec<_> = points.iter().map(|q| hit_spine_segment_of_every_spine(&c, *q, 4.0)).collect(); + old.push(t.elapsed()); + let t = std::time::Instant::now(); + let b: Vec<_> = points.iter().map(|q| hit_spine_segment(&c, *q, 4.0)).collect(); + new.push(t.elapsed()); + assert_eq!(a, b, "{case}"); + } + old.sort(); + new.sort(); + eprintln!("{case}: 500 checks, median of 7: every spine then filter {:?}, selected spines {:?}", old[3], new[3]); + } +} + /// Shift held while a curved segment is dragged sends `perpendicular`. The test drags a path's /// segment with Direct Selection, and a blend spine's segment with Direct Selection and with the /// Anchor Point tool. @@ -2632,3 +2767,30 @@ fn outline_view_marquees_measure_clipped_art_by_the_plain_clipping_path() { let a = marquee(false); assert!(!selects(&a), "preview: {a:?}"); } + +/// #8538: while guides are locked or hidden (`guides` off), a Direct Selection marquee takes +/// neither the anchors nor the crossed segments of a guide path; while guides can be picked, it +/// takes them as on any path. +#[test] +fn a_marquee_skips_the_anchors_and_segments_of_guides_that_cannot_be_picked() { + let (mut d, id) = doc_with_rect(); + if let Some(NodeKind::Path { guide, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *guide = true; + } + let (s, p) = (Selection::default(), paint()); + let marquee = |guides: bool, from: (f64, f64), to: (f64, f64)| { + let cx = ToolContext { guides, ..cx(&d, &s, &p) }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, from.0, from.1)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1)) + }; + let anchors = |items: Value| vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))]; + // Over the corner at (200, 100). + assert_eq!(marquee(false, (150.0, 50.0), (250.0, 150.0)), anchors(json!([])), "locked or hidden: no anchor"); + assert_eq!(marquee(true, (150.0, 50.0), (250.0, 150.0)), anchors(json!([{"id": id.0, "anchors": [[0, 1]]}])), "shown and unlocked"); + // Across the middle of the top edge. + let crossed = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.segments")); + assert!(!crossed(&marquee(false, (140.0, 80.0), (160.0, 120.0))), "locked or hidden: no segment"); + assert!(crossed(&marquee(true, (140.0, 80.0), (160.0, 120.0))), "shown and unlocked"); +} diff --git a/crates/tools/src/distort.rs b/crates/tools/src/distort.rs index 30cb1cd4c5..b4cd0a957c 100644 --- a/crates/tools/src/distort.rs +++ b/crates/tools/src/distort.rs @@ -27,7 +27,7 @@ use crate::Tool; pub use liquify::LiquifyTool; pub use perspective::{PerspectiveGridTool, PerspectiveSelectionTool}; pub use puppet::{PinSet, PuppetWarpTool, mesh_for, mesh_input, rest_and_pins, warp_from_rest}; -pub use width::{WidthTool, stroke_owner}; +pub use width::{KEEPS_SIZE, WidthTool, stroke_owner}; /// Create a distortion tool by id (None = not one of ours). pub fn create(id: &str) -> Option> { diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index 0dc599444f..f93bf3e699 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -829,6 +829,25 @@ impl Tool for LiquifyTool { } } } + /// The options of [`LiquifyParams::from_json`] within its ranges, `diameter` for both sizes, + /// `showBrush`, and `tool` naming this tool. A percentage is a fraction up to 1 and a percent + /// above it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "tool" if value.as_str() == Some(self.params.kind.id()) => Ok(()), + "tool" => Err(format!("`tool` must be `{}`", self.params.kind.id())), + "diameter" | "width" | "height" => c::number(key, value, 0.5, 10_000.0), + "angle" => c::finite(key, value), + "intensity" | "horizontal" | "vertical" => c::number(key, value, 0.0, 100.0), + "detail" => c::number(key, value, 1.0, 10.0), + "simplify" => c::number(key, value, 0.0, 100.0), + "rate" => c::number(key, value, -180.0, 180.0), + "complexity" => c::number(key, value, 0.0, 15.0), + "showBrush" | "usePressure" | "simplifyOn" | "affectAnchors" | "affectIn" | "affectOut" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } /// The tool claims Escape during an Alt-drag that sizes the brush. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { key == ToolKey::Escape && self.sizing.is_some() diff --git a/crates/tools/src/distort/puppet.rs b/crates/tools/src/distort/puppet.rs index 2ca6ec0631..5aae36826e 100644 --- a/crates/tools/src/distort/puppet.rs +++ b/crates/tools/src/distort/puppet.rs @@ -515,6 +515,15 @@ impl Tool for PuppetWarpTool { _ => {} } } + /// `showMesh`, `selectAllPins` and `expand`; `pins` and `selected` are read only. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "showMesh" | "selectAllPins" => c::boolean(key, value), + "expand" => c::number(key, value, 0.0, 1000.0), + _ => Err(c::unknown(key)), + } + } fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index 4ebbac4981..005b8e9473 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -19,8 +19,18 @@ //! A compound path's stroke is the compound's: its members are edited through it, and the width //! points show on every subpath of the stroke (one profile runs along each). The cursor says what a //! drag does: add a width point on a stroke, or move or widen the one under it. +//! +//! A stroke drawn with a brush is left alone, as a width profile does not change it: a press or a +//! double-click on it sends no command and shows why in the status bar ([`KEEPS_SIZE`]). Without +//! Shift, the press or double-click deselects the width points, and the cursor over it offers no +//! edit. Its width points selected before it took the brush show no handles, and Delete, +//! Backspace and Escape do what they do with no width points selected. + +use std::cell::Cell; +use std::sync::Arc; use serde_json::json; +use vectorcraft_brush::Brush; use vectorcraft_doc::{Document, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Point, Vec2}; @@ -107,8 +117,14 @@ pub struct WidthTool { selected: Option<(NodeId, Vec)>, /// The selected width points when the button went down: a dropped press puts them back. before_press: Option<(NodeId, Vec)>, + /// The document's brush library as it was at a revision, so pointer moves and overlays do not + /// parse it again ([`Self::keeps_size`]). + brushes: Cell>, } +/// A document revision and its brush library ([`WidthTool::keeps_size`]). +type BrushesAt = ((u64, u64), Arc>); + /// The object whose stroke path `id` draws with: its compound path, if it is a member of one. pub fn stroke_owner(doc: &Document, id: NodeId) -> NodeId { doc.parent_of(id).filter(|p| doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id) @@ -132,6 +148,9 @@ fn paths_of(doc: &Document, owner: NodeId) -> Vec { out } +/// The status message for a press on a stroke the tool leaves alone ([`WidthTool::keeps_size`]). +pub const KEEPS_SIZE: &str = "The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile."; + /// Side widths (points) of a stroke at fraction `t`. pub fn sides_at(st: &StrokeLayer, t: f64) -> (f64, f64) { let (l, r) = st.profile.as_ref().map(|p| p.at(t)).unwrap_or((1.0, 1.0)); @@ -139,8 +158,46 @@ pub fn sides_at(st: &StrokeLayer, t: f64) -> (f64, f64) { } impl WidthTool { - /// The stroked path nearest to `p` within reach (stroke half-width + a few pixels). - fn spot_at(cx: &ToolContext, p: Point) -> Option { + /// Does `owner`'s stroke draw with a brush ([`vectorcraft_brush::keeps_brush_size`])? A width + /// profile does not change it, so the tool adds and edits no width points on it. The library is + /// parsed once per document revision. + fn keeps_size(&self, cx: &ToolContext, owner: NodeId) -> bool { + let Some(st) = stroke_of(cx.doc, owner).filter(|s| s.brush.is_some()) else { return false }; + let lib = self + .brushes + .take() + .filter(|(rev, _)| *rev == cx.revision) + .map(|(_, lib)| lib) + .unwrap_or_else(|| Arc::new(vectorcraft_brush::library(cx.doc))); + let keeps = vectorcraft_brush::keeps_brush_size(&lib, st); + self.brushes.set(Some((cx.revision, lib))); + keeps + } + + /// Where a press at `p` lands: the nearest stroke the tool edits ([`Self::spot_at`] without + /// brushed strokes), so a plain stroke under a selected brushed one stays reachable. `Err(true)` + /// when only brushed strokes are within reach, `Err(false)` when no stroke is. + fn edit_spot_at(&self, cx: &ToolContext, p: Point) -> Result { + // `spot_at` asks `skip` only about strokes within reach, so one search tells both apart. + let passed_over = Cell::new(false); + let skip = |owner| { + let keeps = self.keeps_size(cx, owner); + passed_over.set(passed_over.get() || keeps); + keeps + }; + Self::spot_at(cx, p, &skip).ok_or_else(|| passed_over.get()) + } + + /// The hovered stroke while the tool still edits it: a brush applied since the last pointer + /// move takes away its handles and its edit cursor. + fn live_hover(&self, cx: &ToolContext) -> Option { + self.hover.filter(|s| !self.keeps_size(cx, s.owner)) + } + + /// The stroked path nearest to `p` within reach (stroke half-width + a few pixels), passing over + /// the strokes whose owner `skip` returns true for. `skip` is asked only about strokes within + /// reach. + fn spot_at(cx: &ToolContext, p: Point, skip: &dyn Fn(NodeId) -> bool) -> Option { let editable = cx.doc.editable(); let consider = |id: NodeId| -> Option<(f64, Spot)> { if !editable(id) { @@ -156,7 +213,7 @@ impl WidthTool { return None; } let (sub, t, q, tan, d) = nearest_fraction(path, p)?; - if d > reach { + if d > reach || skip(owner) { return None; } let (left, right) = sides_at(st, t); @@ -297,12 +354,22 @@ impl Tool for WidthTool { let p = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = Self::spot_at(cx, p); + // A brushed stroke takes no width points, so the cursor offers no edit over it. + self.hover = self.edit_spot_at(cx, p).ok(); vec![] } PointerKind::TripleClick => vec![], PointerKind::DoubleClick => { - let Some(spot) = Self::spot_at(cx, p) else { return vec![] }; + let spot = match self.edit_spot_at(cx, p) { + Ok(spot) => spot, + Err(false) => return vec![], + Err(true) => { + if !ev.mods.shift { + self.selected = None; + } + return vec![Action::Status(KEEPS_SIZE.into())]; + } + }; let Some((w, _)) = Self::hit(cx, &spot, p) else { self.selected = Some((spot.owner, vec![spot.t])); return vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "t": spot.t}))]; @@ -312,11 +379,14 @@ impl Tool for WidthTool { } PointerKind::Down => { self.before_press = self.selected.clone(); - let Some(spot) = Self::spot_at(cx, p) else { - if !ev.mods.shift { - self.selected = None; + let spot = match self.edit_spot_at(cx, p) { + Ok(spot) => spot, + Err(brushed) => { + if !ev.mods.shift { + self.selected = None; + } + return if brushed { vec![Action::Status(KEEPS_SIZE.into())] } else { vec![] }; } - return vec![]; }; let drag = match Self::hit(cx, &spot, p) { Some((w, part)) => { @@ -399,11 +469,12 @@ impl Tool for WidthTool { } /// Delete/Backspace remove the selected width points and Escape deselects them; with none /// selected the keys do what they do with other tools (Clear deletes the selected objects, and - /// Escape leaves isolation mode, for one). + /// Escape leaves isolation mode, for one). Width points of a brushed stroke, which show no + /// handles, count as none selected. fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { matches!(key, ToolKey::Delete | ToolKey::Backspace | ToolKey::Escape) && self.drag.is_none() - && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty()) + && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty() && !self.keeps_size(cx, *id)) } /// A dropped press ends the drag, and the width points selected when the button went down are /// selected again. @@ -426,12 +497,16 @@ impl Tool for WidthTool { return vec![]; } self.selected = None; + if self.keeps_size(cx, id) { + return vec![]; + } vec![Action::Exec("stroke.widthPoint.remove".into(), json!({"id": id.0, "indices": indices}))] } fn overlays(&self, cx: &ToolContext) -> Vec { let mut out = vec![]; let r = cx.tol(4.0); - let focus = self.drag.as_ref().map(|d| d.spot).or(self.hover); + let hover = self.live_hover(cx); + let focus = self.drag.as_ref().map(|d| d.spot).or(hover); // Every subpath's width points of the stroke under the pointer, and of the selected ones'. let show = |owner: NodeId, out: &mut Vec| { for w in Self::all_points(cx, owner) { @@ -445,8 +520,11 @@ impl Tool for WidthTool { if let Some(s) = focus { show(s.owner, &mut out); } + // Width points selected before their stroke took a brush show no handles: the tool no + // longer edits them. if let Some((owner, _)) = &self.selected && focus.is_none_or(|s| s.owner != *owner) + && !self.keeps_size(cx, *owner) { show(*owner, &mut out); } @@ -457,7 +535,7 @@ impl Tool for WidthTool { if cx.measurement_labels { out.push(Overlay::Measure { p: q + d.spot.n * (d.left + r * 3.0), text: format!("W: {}", cx.stroke_unit.readout(d.left + d.right)) }); } - } else if let Some(h) = &self.hover { + } else if let Some(h) = &hover { out.push(Overlay::Line { a: h.p + h.n * h.left, b: h.p - h.n * h.right, color: BLUE, dashed: true }); out.push(Overlay::Path { path: diamond(h.p, r), color: BLUE, width: 1.0, dashed: false }); } @@ -468,7 +546,7 @@ impl Tool for WidthTool { return Cursor::WidthPoint; } // The stroke under the pointer, as the last move found it (no search every frame). - match self.hover { + match self.live_hover(cx) { Some(spot) if Self::hit(cx, &spot, p).is_some() => Cursor::WidthPoint, Some(_) => Cursor::WidthAdd, None => Cursor::Width, @@ -538,6 +616,169 @@ mod tests { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 220.0)), vec![Action::Commit]); } + /// A stroke drawn with a brush of the library (the 3 pt. Round calligraphic brush) is left + /// alone: a press or a double-click sends no command and says why. A brush name the library + /// lacks draws a plain stroke, which the tool edits as usual. + #[test] + fn brushed_stroke_is_left_alone_with_a_reason() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + let refused = vec![Action::Status(KEEPS_SIZE.into())]; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), refused); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 150.0, 220.0)), vec![], "no drag began"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 220.0)), vec![]); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 201.0)), refused); + + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("No Such Brush".into()); + let c = cx(&d, &s, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + } + + /// A selected brushed stroke lying on a plain one does not hide the plain one: a press there + /// edits the plain stroke. + #[test] + fn a_plain_stroke_under_a_selected_brushed_one_stays_reachable() { + let (mut d, _) = doc_line(); + let l = d.layers[0].id; + let brushed = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 200.0), Point::new(300.0, 200.0)], false)); + d.insert(Some(l), 0, Node::path(brushed, path, ap)).unwrap(); + let (s, p) = (Selection { objects: vec![brushed], ..Default::default() }, paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::WidthAdd); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + } + + /// A brush applied to the hovered stroke, with the pointer still, takes away its handles and its + /// edit cursor before the next pointer move. + #[test] + fn a_brush_applied_under_a_still_pointer_takes_away_the_hover() { + let (mut d, id) = doc_line(); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::WidthAdd); + assert!(!t.overlays(&c).is_empty()); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::Width); + assert!(t.overlays(&c).is_empty()); + } + + /// The brush library is read once per document revision: a brush added to the library under a + /// new revision is seen, so a stroke naming it is then left alone. + #[test] + fn a_brush_added_to_the_library_is_seen_at_the_next_revision() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("Added Later".into()); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 201.0)); + let mut lib = vectorcraft_brush::library(&d); + let mut added = lib[0].clone(); + added.name = "Added Later".into(); + lib.push(added); + vectorcraft_brush::store(&mut d, &lib); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Status(KEEPS_SIZE.into())]); + } + + /// Width points selected before the stroke took a brush show no handles and count as none + /// selected: the tool leaves Delete and Escape to the app, and removes none. + #[test] + fn delete_leaves_the_width_points_of_a_brushed_stroke() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().profile = + Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 1.0, 1.0)] }); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + assert!(t.claims_key(&c, ToolKey::Delete), "a width point is selected"); + assert!(!t.overlays(&c).is_empty(), "the selected point shows its handles"); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert!(t.overlays(&c).is_empty(), "no handles show on a stroke the tool no longer edits"); + for key in [ToolKey::Delete, ToolKey::Backspace, ToolKey::Escape] { + assert!(!t.claims_key(&c, key), "{key:?} is the app's"); + } + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![]); + assert!(t.selected.is_none()); + } + + /// With Shift held, a press or a double-click on a brushed stroke keeps the width points of + /// another stroke selected, as a Shift-press that misses every stroke does. + #[test] + fn shift_on_a_brushed_stroke_keeps_the_selected_width_points() { + let (mut d, _) = doc_three_points(); + let l = d.layers[0].id; + let other = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 400.0), Point::new(300.0, 400.0)], false)); + d.insert(Some(l), 0, Node::path(other, path, ap)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + let kept = t.selected.clone(); + assert!(kept.is_some(), "the plain stroke's width point is selected"); + for kind in [PointerKind::Down, PointerKind::DoubleClick] { + assert_eq!(t.pointer(&c, &ev(kind, 200.0, 401.0, shift)), vec![Action::Status(KEEPS_SIZE.into())]); + assert_eq!(t.selected, kept, "{kind:?} with Shift keeps the selection"); + } + assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, 200.0, 401.0, Mods::default())), vec![Action::Status(KEEPS_SIZE.into())]); + assert!(t.selected.is_none(), "a double-click without Shift deselects"); + } + + /// A press on a brushed stroke deselects the width points of another stroke, as a press that + /// misses every stroke does, so a later Delete does not edit that other stroke. The cursor over + /// a brushed stroke offers no edit. + #[test] + fn a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit() { + let (mut d, _) = doc_three_points(); + let l = d.layers[0].id; + let other = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 400.0), Point::new(300.0, 400.0)], false)); + d.insert(Some(l), 0, Node::path(other, path, ap)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + assert!(t.claims_key(&c, ToolKey::Delete), "the plain stroke's width point is selected"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 401.0)), vec![Action::Status(KEEPS_SIZE.into())]); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 401.0)); + assert!(!t.claims_key(&c, ToolKey::Delete), "nothing is left to delete"); + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![]); + + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 200.0, 401.0)); + assert_eq!(t.cursor(&c, Point::new(200.0, 401.0), Mods::default()), Cursor::Width); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 220.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(220.0, 201.0), Mods::default()), Cursor::WidthAdd, "the plain stroke still offers one"); + } + #[test] fn alt_drag_changes_one_side_and_move_slides() { let (mut d, id) = doc_line(); diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 58664704ad..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 { @@ -168,7 +185,7 @@ impl AnchorTool { | State::SpineHandle { id, .. } | State::Reshape { id, .. } => Some((cx.selection.contains(id), cx.doc.index_path(id))), }; - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let candidate = if let Some((ai, out)) = Self::spine_handle(cx, &path, p, point) { State::SpineHandle { id, ai, out, start: p, began: false } } else if let Some(ai) = Self::spine_point(&path, p, point) { @@ -192,7 +209,7 @@ impl AnchorTool { /// tool switch. Show the handles on selected blends so they stay editable. fn spine_overlays(cx: &ToolContext) -> Vec { let mut out = vec![]; - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let anchors: Vec<_> = path.anchors().filter(|(si, _, _)| *si == 0).collect(); if !cx.handles_multiple && anchors.len() > 1 { continue; @@ -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/family.rs b/crates/tools/src/draw2/family.rs index 8bdbb4db0f..87c11abba9 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -529,11 +529,32 @@ impl Tool for FamilyTool { } } } + /// The options the tool shows ([`Self::options`]): those of the arc, the spiral or the grid. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + let skew = vectorcraft_geom::shapes::GRID_SKEW_MAX; + match key { + "lengthX" | "lengthY" => c::number(key, v, 1e-9, 1e6), + "width" | "height" => c::positive(key, v, 1e6), + "reference" => c::whole(key, v, 0, 8), + "baseAlong" => c::one_of(key, v, &["x", "y", "X", "Y"]), + "slope" => c::number(key, v, -100.0, 100.0), + "decay" => c::number(key, v, 5.0, 99.99), + "segments" => c::whole(key, v, 2, 1000), + "rows" | "concentric" | "columns" | "radial" => c::whole(key, v, 0, 999), + "rowSkew" | "concentricSkew" | "columnSkew" | "radialSkew" => c::number(key, v, -skew, skew), + _ => c::boolean(key, v), + } + } } -/// Arc segment length from a dialog or preference value. +/// Arc segment length from a dialog or preference value, from 1e-9 to 1e6 pt (as the option check +/// takes it). fn arc_length(v: &Value, current: f64) -> f64 { - v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().max(1e-9)) + v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().clamp(1e-9, 1e6)) } /// A grid's Default Size side from option value `v`: a finite positive length (at most 1e6 pt), @@ -578,6 +599,28 @@ mod tests { } } + /// A number `tool.setOption` takes is kept as given, and a number the tool would keep as + /// another value is refused: `decay` past 99.99 is an error. + #[test] + fn family_tools_keep_the_numbers_their_option_check_takes() { + let tries = [-1e9, -150.0, -100.0, -1.0, 0.0, 1e-12, 0.5, 1.0, 2.0, 5.0, 8.0, 99.99, 100.0, 120.0, 150.0, 999.0, 1000.0, 1e6, 1e9]; + for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] { + let defaults = FamilyTool::new(id).options(); + for (k, _) in defaults.as_object().into_iter().flatten().filter(|(_, v)| v.is_number()) { + for n in tries { + let mut t = FamilyTool::new(id); + if t.check_option(k, &json!(n)).is_ok() { + t.set_option(k, &json!(n)); + assert_eq!(t.options()[k].as_f64(), Some(n), "{id} `{k}` = {n}"); + } + } + } + } + let t = FamilyTool::new("spiral"); + assert_eq!(t.check_option("decay", &json!(120.0)).err(), Some("`decay` must be a number from 5 to 99.99".into())); + assert!(t.check_option("decay", &json!(99.99)).is_ok()); + } + #[test] fn normalized_spiral_decay_preserves_existing_capped_paths_within_roundoff() { for requested in [100.0, 150.0] { @@ -1067,6 +1110,10 @@ mod tests { "fillArc": true, }) ); + // A length past 1e6 pt is kept at 1e6, which `tool.setOption` takes back. + t.set_option("lengthX", &json!(-1e9)); + assert_eq!(t.options()["lengthX"], json!(1e6)); + assert_eq!(t.check_option("lengthX", &t.options()["lengthX"]), Ok(())); } /// While an arc is dragged out, C switches it between open and closed, F switches its base diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 502fd16dbd..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![], @@ -2059,6 +2107,32 @@ impl Tool for GestureTool { _ => {} } } + /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity that the + /// Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`). + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let smooth_store = key == "smoothFidelity" && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); + if !smooth_store && self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + match key { + "fidelity" => c::number(key, v, super::min_fidelity(self.id), 100.0), + "smoothFidelity" => c::number(key, v, super::min_fidelity("smooth"), 100.0), + "size" => c::number(key, v, 0.1, 1000.0), + "sizeVariation" => c::number(key, v, 0.0, 1000.0), + "angle" => c::number(key, v, -180.0, 180.0), + "roundness" => c::number(key, v, if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0), + "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), + "angleVariation" => c::number(key, v, 0.0, 180.0), + "roundnessVariation" => c::number(key, v, 0.0, 100.0), + // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size + // take any mode (`set_option`). + "sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]), + "sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)), + "fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 550e7f9d32..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 @@ -3087,6 +3184,20 @@ fn the_eraser_tip_follows_its_variation_modes() { [&o["angleMode"], &o["angleVariation"], &o["roundnessMode"], &o["roundnessVariation"], &o["sizeMode"], &o["sizeVariation"]], [&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)] ); + // `tool.setOption` takes back what the tool reports, and refuses a mode or Variation it does + // not take. + let reported = o.as_object().unwrap().clone(); + assert_eq!(t.check_options(&reported), Ok(())); + for mode in Variation::ALL { + for k in ["sizeMode", "angleMode", "roundnessMode"] { + assert_eq!(t.check_option(k, &json!(mode.id())), Ok(()), "{k} {mode:?}"); + } + } + let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`"; + assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}"))); + assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into())); + assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into())); + assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into())); // A mode it does not have leaves the mode as it was; a Variation is kept within its range. t.set_option("angleMode", &json!("wheel")); t.set_option("roundnessVariation", &json!(500)); diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 4c6a6c6d45..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 { @@ -400,6 +488,18 @@ impl Tool for FlareTool { } } } + /// The switches and [`FLARE_OPTIONS`] within their ranges, the counts whole. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if matches!(key, "raysOn" | "ringsOn") { + return c::boolean(key, v); + } + let Some(&(_, _, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return Err(c::unknown(key)) }; + if is_count(key) && v.as_f64().is_none_or(|n| n.fract() != 0.0) { + return Err(format!("`{key}` must be a whole number from {lo} to {hi}")); + } + c::number(key, v, lo, hi) + } } /// Where a Reshape press landed on a selected path. @@ -1009,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/intertwine.rs b/crates/tools/src/intertwine.rs index 7ea841b4a7..35a0f1747d 100644 --- a/crates/tools/src/intertwine.rs +++ b/crates/tools/src/intertwine.rs @@ -364,6 +364,10 @@ impl Tool for IntertwineTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "prev" { crate::option_check::string_or_null(key, value) } else { Err(crate::option_check::unknown(key)) } + } + fn busy(&self) -> bool { self.dragging } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index b5d7574b1f..0b7bef755f 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -12,6 +12,7 @@ pub mod bbox; pub mod blendwidget; pub mod builder; pub mod catalog; +pub mod circle; pub mod corners; pub mod cropimage; pub mod cut; @@ -27,6 +28,7 @@ pub mod meshedit; pub mod mirror; pub mod nineslice; pub mod objects_on_path; +pub mod option_check; pub mod params; pub mod pathtype; pub mod pen; @@ -40,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; @@ -102,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 @@ -160,6 +167,18 @@ pub trait Tool: Send { Value::Null } fn set_option(&mut self, _key: &str, _value: &Value) {} + /// Whether [`Self::set_option`] takes `value` for option `key` as it is: an error names an + /// option the tool doesn't have, a value of the wrong type or a number out of range + /// (`tool.setOption` checks every option it is given with this before it sets any). A tool + /// without options takes none. + fn check_option(&self, key: &str, _value: &Value) -> Result<(), String> { + Err(option_check::unknown(key)) + } + /// Whether [`Self::set_option`] takes all of `values`, set together in one call: by default + /// each one checked on its own with [`Self::check_option`]. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + values.iter().try_for_each(|(k, v)| self.check_option(k, v)) + } /// Is an interaction in progress (drag, open pen path)? fn busy(&self) -> bool { false @@ -272,8 +291,8 @@ pub trait Tool: Send { false } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the - /// selection, a gradient vector, a Scale, Rotate, Reflect or Shear tool drag), or the - /// Paintbrush's brush. None for a tool with nothing of its own to show. + /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear + /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. fn readout(&self, _cx: &ToolContext) -> Option { None } @@ -365,6 +384,7 @@ pub fn create(id: &str) -> Box { "dimension" => Box::new(dimension::DimensionTool::default()), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath" => Box::new(text::TypeTool::new(id)), "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star" | "lineSegment" => Box::new(shape::ShapeTool::new(id)), + circle::ID => Box::new(circle::CircleTool::default()), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), other => symbolism::create(other) @@ -659,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/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index fe956691e1..dbb6f8bfdf 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -1106,6 +1106,15 @@ impl Tool for ObjectsOnPathTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "pivot" => c::whole(key, value, 0, 8), + "rotate" => c::number(key, value, -360.0, 360.0), + _ => Err(c::unknown(key)), + } + } + fn busy(&self) -> bool { self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() || self.moving.is_some() || self.member.is_some() } diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs new file mode 100644 index 0000000000..dd26fa28f0 --- /dev/null +++ b/crates/tools/src/option_check.rs @@ -0,0 +1,245 @@ +//! Checks of tool option values ([`crate::Tool::check_option`]) and of `tool.setOption`'s +//! parameters. Each error names the option and what it takes. + +use serde_json::{Map, Value}; + +use crate::Tool; + +/// The error for an option the tool doesn't have. +pub fn unknown(key: &str) -> String { + format!("unknown option `{key}`") +} + +/// `v` is a finite number from `lo` to `hi`. +pub fn number(key: &str, v: &Value, lo: f64, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() && (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + } +} + +/// `v` is a finite number. +pub fn finite(key: &str, v: &Value) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() => Ok(()), + _ => Err(format!("`{key}` must be a finite number")), + } +} + +/// `v` is a finite number above 0 and at most `hi`. +pub fn positive(key: &str, v: &Value, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n > 0.0 && n <= hi => Ok(()), + _ => Err(format!("`{key}` must be a number above 0 and at most {hi}")), + } +} + +/// `v` is a whole number (written without a fraction) from `lo` to `hi`. +pub fn whole(key: &str, v: &Value, lo: u64, hi: u64) -> Result<(), String> { + match v.as_u64() { + Some(n) if (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a whole number from {lo} to {hi}")), + } +} + +/// `v` is true or false. +pub fn boolean(key: &str, v: &Value) -> Result<(), String> { + if v.is_boolean() { Ok(()) } else { Err(format!("`{key}` must be true or false")) } +} + +/// `v` is one of the strings `choices`. +pub fn one_of(key: &str, v: &Value, choices: &[&str]) -> Result<(), String> { + if v.as_str().is_some_and(|s| choices.contains(&s)) { + Ok(()) + } else { + let list: Vec = choices.iter().map(|c| format!("`{c}`")).collect(); + Err(format!("`{key}` must be one of {}", list.join(", "))) + } +} + +/// `v` is a string, or null. +pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { + if v.is_string() || v.is_null() { Ok(()) } else { Err(format!("`{key}` must be a string or null")) } +} + +/// What `tool.setOption {tool?, key?, value?, values?}` sets: the tool named (none: the active +/// tool) and the options, `key` and `value` among `values`. A parameter of the wrong type, a +/// `value` without a `key` or a `key` without a `value`, and an option given both as `key` and in +/// `values` are errors, and so are parameters that are not an object. With none of `key` and +/// `values`, or with no parameters (null), the options are empty: the command reads them. +pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { + if !p.is_object() && !p.is_null() { + return Err(format!("the params must be an object, not {}", shown(p))); + } + let tool = match p.get("tool") { + None => None, + Some(t) => Some(t.as_str().ok_or("`tool` must be a tool id")?), + }; + let mut values = match p.get("values") { + None => Map::new(), + Some(v) => v.as_object().cloned().ok_or("`values` must be an object")?, + }; + match (p.get("key"), p.get("value")) { + (None, None) => {} + (Some(k), v) => { + let k = k.as_str().ok_or("`key` must be a string")?; + let v = v.ok_or_else(|| format!("`value` is missing for `{k}`"))?; + if values.contains_key(k) { + return Err(format!("`{k}` is given both as `key` and in `values`")); + } + values.insert(k.to_string(), v.clone()); + } + (None, Some(_)) => return Err("`value` needs a `key`".into()), + } + Ok((tool, values)) +} + +/// The JSON text of `v` as a parameter error shows it: cut to 40 characters, with `…` when it was +/// longer. The text is written only up to the cut. +fn shown(v: &Value) -> String { + struct Cut { + text: String, + left: usize, + } + impl std::fmt::Write for Cut { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for c in s.chars() { + if self.left == 0 { + return Err(std::fmt::Error); + } + self.left -= 1; + self.text.push(c); + } + Ok(()) + } + } + let mut out = Cut { text: String::new(), left: 40 }; + if std::fmt::Write::write_fmt(&mut out, format_args!("{v}")).is_err() { + out.text.push('…'); + } + out.text +} + +/// Check every one of `values` as an option of `tool` ([`Tool::check_options`]), before any is +/// set: the first one the tool doesn't take is an error that names the tool. +pub fn check_values(tool: &dyn Tool, values: &Map) -> Result<(), String> { + tool.check_options(values).map_err(|e| format!("tool `{}`: {e}", tool.id())) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn numbers_are_checked_against_their_range() { + assert!(number("fidelity", &json!(0.05), 0.05, 100.0).is_ok()); + assert!(number("fidelity", &json!(100), 0.05, 100.0).is_ok()); + for bad in [json!(-3), json!(1e9), json!("abc"), json!(true), json!(null), json!(0.04)] { + assert_eq!(number("fidelity", &bad, 0.05, 100.0), Err("`fidelity` must be a number from 0.05 to 100".into()), "{bad}"); + } + assert!(whole("sides", &json!(3), 3, 1000).is_ok()); + for bad in [json!(2), json!(3.5), json!(1001), json!(-1), json!("6")] { + assert!(whole("sides", &bad, 3, 1000).is_err(), "{bad}"); + } + assert!(positive("width", &json!(0), 1e6).is_err()); + assert!(positive("width", &json!(1e6), 1e6).is_ok()); + assert!(finite("angle", &json!(720)).is_ok()); + assert!(finite("angle", &json!("720")).is_err()); + } + + #[test] + fn other_values_are_checked_by_kind() { + assert!(boolean("fill", &json!(false)).is_ok()); + assert_eq!(boolean("fill", &json!(0)), Err("`fill` must be true or false".into())); + assert!(one_of("axis", &json!("free"), &["vertical", "free"]).is_ok()); + assert_eq!(one_of("axis", &json!("diagonal"), &["vertical", "free"]), Err("`axis` must be one of `vertical`, `free`".into())); + assert!(string_or_null("prev", &json!(null)).is_ok()); + assert!(string_or_null("prev", &json!(3)).is_err()); + } + + /// Every tool takes back the options it reports, each on its own and all together: a dialog's + /// OK sends every field the tool showed it. The state a tool reports and doesn't take (the + /// picked mesh points, the text being edited, the pins, the queue of files to place) is left + /// out. + #[test] + fn every_tool_takes_the_options_it_reports() { + const TYPE: &[&str] = &["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; + const READ_ONLY: &[(&[&str], &[&str])] = &[ + (&["directSelection", "groupSelection", "lasso", "polygonalLasso", "mesh", "magicWand"], &["meshPoints"]), + (TYPE, &["editing"]), + (&["puppetWarp"], &["pins", "selected"]), + // With nothing queued, `current` (0) is no file's index either. + (&["place"], &["count", "current", "name", "width", "height", "names"]), + ]; + let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); + // Tools that `create` makes and the catalog doesn't list. + let extra = ["place", "dimension", crate::cropimage::ID, "intertwine"]; + let mut refused = Vec::new(); + let mut check = |id: &str, tool: &dyn Tool, after: &str| { + let Some(mut options) = tool.options().as_object().cloned() else { return }; + options.retain(|k, _| !read_only(id, k)); + for (k, v) in &options { + if let Err(e) = tool.check_option(k, v) { + refused.push(format!("tool `{id}`{after}, option `{k}` = {v}: {e}")); + } + } + if let Err(e) = check_values(tool, &options) { + refused.push(format!("{e}{after}")); + } + }; + for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { + let tool = crate::create(id); + check(id, tool.as_ref(), ""); + // A number set past either end, or a true-or-false option flipped, is still taken back + // as the tool then reports it. + let Some(defaults) = tool.options().as_object().cloned() else { continue }; + for (k, v) in defaults.iter().filter(|(k, _)| !read_only(id, k)) { + let tries = match v { + Value::Number(_) => vec![json!(-1e9), json!(1e9)], + Value::Bool(b) => vec![json!(!b)], + _ => continue, + }; + for value in tries { + let mut changed = crate::create(id); + changed.set_option(k, &value); + check(id, changed.as_ref(), &format!(" after setting `{k}` to {value}")); + } + } + } + assert!(refused.is_empty(), "{}", refused.join("\n")); + } + + #[test] + fn set_option_params_reads_the_tool_and_the_options() { + let p = json!({"tool": "smooth", "key": "fidelity", "value": 2, "values": {"x": 1}}); + let (tool, values) = set_option_params(&p).unwrap(); + assert_eq!(tool, Some("smooth")); + assert_eq!(Value::Object(values), json!({"fidelity": 2, "x": 1})); + let empty = json!({}); + let (tool, values) = set_option_params(&empty).unwrap(); + assert!(tool.is_none() && values.is_empty()); + // Omitted parameters arrive as null: a read, like `{}`. + let (tool, values) = set_option_params(&Value::Null).unwrap(); + assert!(tool.is_none() && values.is_empty()); + for (bad, got) in [(json!(true), "true"), (json!(7), "7"), (json!([]), "[]"), (json!("x"), "\"x\"")] { + assert_eq!(set_option_params(&bad).err(), Some(format!("the params must be an object, not {got}")), "{bad}"); + } + // A long value is shown cut, as the other parameter errors show it. + let long = json!("a".repeat(100)); + let shown = format!("\"{}…", "a".repeat(39)); + assert_eq!(set_option_params(&long).err(), Some(format!("the params must be an object, not {shown}"))); + assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); + assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); + assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); + assert_eq!(set_option_params(&json!({"key": "fill"})).err(), Some("`value` is missing for `fill`".into())); + assert_eq!(set_option_params(&json!({"value": 1})).err(), Some("`value` needs a `key`".into())); + assert_eq!( + set_option_params(&json!({"key": "fill", "value": true, "values": {"fill": false}})).err(), + Some("`fill` is given both as `key` and in `values`".into()) + ); + // An explicit null is a value: the Type tool's triggers take one. + assert!(set_option_params(&json!({"key": "stopEditing", "value": null})).is_ok()); + } +} diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index ada9754c1d..7b12599b62 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -29,6 +29,7 @@ //! the other art and of the path being drawn, into line with them, onto the construction guides //! through the last anchor; with Shift held it slides along its 45° step into line. Hovering shows //! where the next one would go. +//! While a drag pulls a handle out, the Info panel shows it from the anchor to the handle's end. use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; @@ -62,6 +63,10 @@ pub struct PenTool { /// The pointer has moved past the drag threshold since the press: a press released inside it /// is a click, so the anchor stays a corner without handles. dragged: bool, + /// The handle a drag past the threshold is pulling out, from the anchor it shapes to the + /// handle's end as last previewed (the outgoing handle, or the incoming one of the first + /// anchor closing the path): what the Info panel shows ([`Tool::readout`]). + vector: Option, /// The last anchor of the path being drawn, while a click retracts its outgoing handle or a /// drag pulls a new one out: (path, subpath, anchor, its position). handle: Option<(NodeId, usize, usize, Point)>, @@ -256,6 +261,12 @@ impl Tool for PenTool { fn ends_on_escape(&self, cx: &ToolContext) -> bool { self.active(cx).is_some() } + /// The handle a drag is pulling out of the anchor it shapes: the outgoing handle of a new or + /// added anchor or of the last anchor, or the incoming handle of the first anchor closing the + /// path. None for a click, a hover or an Alt gesture. + fn readout(&self, _cx: &ToolContext) -> Option { + self.vector.filter(|_| self.dragged && (self.drag.is_some() || self.handle.is_some())).map(crate::Readout::drag) + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let tol = cx.tol(5.0).max(cx.point_tol()); // The path a press began is the selected one by the next event. @@ -292,6 +303,7 @@ impl Tool for PenTool { self.last = ev.pos; self.pressed = ev.pos; self.dragged = false; + self.vector = None; if let Some((id, si, first, last, _)) = active { let end = last_anchor(cx, id, Some(si)); let closing_end = end.filter(|(_, ai)| *ai > 0).map(|_| first); @@ -391,6 +403,7 @@ impl Tool for PenTool { if ev.mods.shift { h = a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle); } + self.vector = Some(h - a); return vec![set_out_handle(id, si, ai, h)]; } let Some(Place { at: mut a, path, subpath, closing, mut moved }) = self.drag else { return vec![] }; @@ -412,6 +425,8 @@ impl Tool for PenTool { if ev.mods.shift { out_h = a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle); } + // A closing drag shapes the first anchor's incoming handle, which mirrors the pointer. + self.vector = Some(if closing { a - out_h } else { out_h - a }); let alt = ev.mods.alt; let Some(id) = path else { // First anchor of a new path: re-issue create with handles. @@ -436,6 +451,7 @@ impl Tool for PenTool { } PointerKind::Up => { self.snap.clear(); + self.vector = None; if let Some(mut t) = self.convert.take() { return t.pointer(cx, ev); } @@ -471,6 +487,7 @@ impl Tool for PenTool { self.first = None; self.handle = None; self.convert = None; + self.vector = None; self.snap.clear(); vec![] } @@ -482,6 +499,7 @@ impl Tool for PenTool { let placing = self.drag.take().is_some(); self.first = None; let handling = self.handle.take().is_some(); + self.vector = None; // Finish the preview as it stands; clearing state alone leaves its transaction open. let mut acts = self.convert.take().map(|mut t| t.deactivate(cx)).unwrap_or_default(); if placing || handling { @@ -507,10 +525,12 @@ impl Tool for PenTool { && let (Some((id, _, _, last, out)), Some(h)) = (self.active(cx), self.hover) { if cx.pen_rubber_band { + // The segment a click at `h` adds: it leaves the last anchor along its outgoing + // handle and arrives at the new corner anchor without a handle. let mut bp = BezPath::new(); bp.move_to(last); if out.distance(last) > 1e-9 { - bp.quad_to(out, h); + bp.curve_to(out, h, h); } else { bp.line_to(h); } @@ -611,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; @@ -690,7 +710,7 @@ fn auto_add_delete(cx: &ToolContext, p: Point, m: Mods, tol: f64) -> Option Option> { - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let Some(NodeKind::Blend { children, spec }) = cx.doc.node(id).map(|n| &n.kind) else { continue }; let keys = vectorcraft_doc::live::blend_spine(children, spec).and_then(|(_, a)| a).unwrap_or_default(); if let Some((_, ai, _)) = path.anchors().find(|(_, _, a)| a.p.distance(p) <= tol) { diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index be8468e379..7b804685b3 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -865,6 +865,27 @@ fn anchors_snap_to_smart_guides() { assert_eq!(a[1], Action::Preview("path.create".into(), json!({"anchors": [{"x": 100.0, "y": 100.0}]}))); } +/// The rubber band after a smooth anchor is the curve the click then adds: it leaves along the +/// anchor's outgoing handle and arrives at the new corner anchor without a handle, so the segment +/// keeps its shape when the anchor goes down (#8296). +#[test] +fn rubber_band_is_the_segment_a_click_adds() { + let (last, out) = (Point::new(60.0, 300.0), Point::new(110.0, 250.0)); + let sub = vectorcraft_geom::SubPath::new(vec![Anchor::corner(Point::new(10.0, 300.0)), Anchor::smooth(last, out)], false); + let (d, id, s) = drawing(sub); + let p = paint(); + let cx = ToolContext { zoom: 1.0, smart_guides: false, snap_to_point: false, snap_to_pixel: false, snap_to_grid: false, ..cx(&d, &s, &p) }; + let h = Point::new(237.0, 361.0); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, h.x, h.y)); + let band: Vec<_> = + t.overlays(&cx).into_iter().filter_map(|o| if let Overlay::Path { path, .. } = o { Some(path.elements().to_vec()) } else { None }).collect(); + assert_eq!(band, vec![vec![vectorcraft_geom::PathEl::MoveTo(last), vectorcraft_geom::PathEl::CurveTo(out, h, h)]]); + // The click adds a corner anchor there: the segment drawn is the one previewed. + let a = click(&mut t, &cx, h.x, h.y, Mods::default()); + assert_eq!(a[1], Action::Preview("path.appendAnchor".into(), json!({"id": id.0, "x": h.x, "y": h.y, "subpath": 0}))); +} + /// With Enable Rubber Band off, the preview segment is hidden but Measurement Labels still shows /// the D / Angle / dX / dY readout at the snapped point before the next click. #[test] @@ -1062,3 +1083,128 @@ fn continuing_a_compound_member_at_its_first_anchor_reverses_that_path_by_id() { ); assert_eq!((pen.path, pen.subpath), (Some(a), Some(0))); } + +/// A context with snapping off, so each point goes where the pointer is. +fn plain<'a>(d: &'a vectorcraft_doc::Document, s: &'a Selection, p: &'a crate::PaintDefaults) -> ToolContext<'a> { + ToolContext { zoom: 1.0, smart_guides: false, snap_to_point: false, snap_to_pixel: false, snap_to_grid: false, ..cx(d, s, p) } +} + +fn drag_readout(dx: f64, dy: f64) -> Option { + Some(crate::Readout::Drag { dx, dy }) +} + +/// The Info panel shows the handle a drag pulls out of a new anchor, from the anchor to the +/// handle's end, once the drag passes the threshold and until the button comes up. +#[test] +fn info_readout_tracks_the_handle_of_a_new_anchor() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + assert_eq!(t.readout(&cx), None, "hovering"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + assert_eq!(t.readout(&cx), None, "pressed"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 101.0, 101.0)); + assert_eq!(t.readout(&cx), None, "inside the drag threshold"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 60.0)); + let r = t.readout(&cx); + assert_eq!(r, drag_readout(30.0, -40.0)); + let (dist, angle) = r.and_then(|r| r.distance_angle()).unwrap_or_default(); + assert!((dist - 50.0).abs() < 1e-9 && (angle - 53.130_102_354_155_98).abs() < 1e-9, "{dist} {angle}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 60.0)); + assert_eq!(t.readout(&cx), None, "released"); + // A click shows nothing. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 201.0, 200.0)); + assert_eq!(t.readout(&cx), None); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 201.0, 200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 250.0, 250.0)); + assert_eq!(t.readout(&cx), None, "hovering after a click"); +} + +/// An anchor added to the path being drawn and the first anchor closing it: the handle the drag +/// shapes is measured from the anchor it belongs to. +#[test] +fn info_readout_tracks_added_and_closing_anchors() { + let pts = [Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(200.0, 400.0)]; + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&pts, false)); + let p = paint(); + let cx = plain(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 400.0)); + assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(c, _)] if c == "path.appendAnchor"), "{a:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 330.0, 440.0)); + assert_eq!(t.readout(&cx), drag_readout(30.0, 40.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 330.0, 440.0)); + assert_eq!(t.readout(&cx), None); + // A press on the first anchor, a pixel off it, closes: the readout is that anchor's incoming + // handle, which mirrors the pointer. + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 101.0, 301.0)); + assert!(matches!(&a[..], [Action::Begin(c), _] if c == "Close Path"), "{a:?}"); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 260.0)); + let [Action::Preview(c, v)] = acts.as_slice() else { panic!("not a close preview: {acts:?}") }; + assert_eq!((c.as_str(), &v["in"]), ("path.close", &json!([70.0, 340.0]))); + assert_eq!(t.readout(&cx), drag_readout(-30.0, 40.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 260.0)); + assert_eq!(t.readout(&cx), None); +} + +/// A drag from the last anchor pulls its outgoing handle out on its own; with Shift the readout +/// gives the constrained handle the preview shows. +#[test] +fn info_readout_tracks_the_last_anchor_handle() { + let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0), Point::new(60.0, 300.0)], false)); + let p = paint(); + let cx = plain(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 60.0, 300.0)); + assert_eq!(t.readout(&cx), None, "a click retracts the handle"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 70.0, 280.0)), vec![set_out(id, 1, 70.0, 280.0)]); + assert_eq!(t.readout(&cx), drag_readout(10.0, -20.0)); + let shift = Mods { shift: true, ..Mods::default() }; + // 26.6° from the anchor: Shift turns it to the 45° step nearest. + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 80.0, 290.0).with_mods(shift)); + let [Action::Preview(_, v)] = acts.as_slice() else { panic!("not a handle preview: {acts:?}") }; + let (hx, hy) = (v["x"].as_f64().unwrap_or(f64::NAN), v["y"].as_f64().unwrap_or(f64::NAN)); + assert!(((hx - 60.0) + (hy - 300.0)).abs() < 1e-9, "constrained to 45°: {v}"); + assert_eq!(t.readout(&cx), drag_readout(hx - 60.0, hy - 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 80.0, 290.0)); + assert_eq!(t.readout(&cx), None); +} + +/// Space moves the anchor and its handles together, so the handle keeps its length; Alt leaves +/// the incoming handle behind and the readout follows the outgoing one. +#[test] +fn info_readout_follows_space_and_alt() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 420.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 450.0, 420.0)); + assert_eq!(t.readout(&cx), drag_readout(50.0, 0.0)); + let space = Mods { space: true, ..Mods::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 450.0, 380.0).with_mods(space)); + assert_eq!(t.readout(&cx), drag_readout(50.0, 0.0), "the anchor moved with the handle"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 460.0, 400.0)); + assert_eq!(t.readout(&cx), drag_readout(60.0, 20.0), "measured from the moved anchor"); + let alt = Mods { alt: true, ..Mods::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 400.0, 450.0).with_mods(alt)); + assert_eq!(t.readout(&cx), drag_readout(0.0, 70.0)); +} + +/// A dropped press and switching tools clear the readout. +#[test] +fn info_readout_clears_on_a_dropped_press_and_deactivate() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert_eq!(t.readout(&cx), drag_readout(20.0, 0.0)); + t.drop_press(&cx); + assert_eq!(t.readout(&cx), None, "dropped"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 130.0)); + assert_eq!(t.readout(&cx), drag_readout(0.0, 30.0)); + t.deactivate(&cx); + assert_eq!(t.readout(&cx), None, "deactivated"); +} diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index 66d3fbc5f1..813ec99429 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -188,6 +188,33 @@ impl Tool for PlaceTool { } } + /// A queue whose every entry has its `params` object and a finite `width` and `height`, and + /// `current` within the queue held. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "queue" => check_queue(value).map(drop), + "current" => check_current(value, self.entries.len()), + _ => Err(crate::option_check::unknown(key)), + } + } + + /// As [`Self::check_option`], except that a `current` given with a `queue` is an index into + /// that queue (the queue is set first). + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let mut held = self.entries.len(); + if let Some(queue) = values.get("queue") { + held = check_queue(queue)?; + } + for (k, v) in values { + match k.as_str() { + "queue" => {} + "current" => check_current(v, held)?, + _ => self.check_option(k, v)?, + } + } + Ok(()) + } + /// Switching tools discards what the cursor holds. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.entries.clear(); @@ -196,6 +223,35 @@ impl Tool for PlaceTool { } } +/// The number of files `queue` holds, or an error when an entry lacks its `params` object or a +/// finite `width` and `height`. +fn check_queue(queue: &Value) -> Result { + let entry = |e: &Value| { + e.get("params").is_some_and(Value::is_object) + && e.get("name").is_none_or(Value::is_string) + && ["width", "height"].iter().all(|k| e.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite)) + }; + let entries = match queue.get("entries") { + None => Some(0), + Some(e) => e.as_array().filter(|a| a.iter().all(entry)).map(Vec::len), + }; + match entries { + Some(n) if queue.is_object() && queue.get("prev").is_none_or(Value::is_string) => Ok(n), + _ => Err("`queue` must be {entries: [{params, name, width, height}], prev?}: each entry with a params object and a finite \ + width and height" + .into()), + } +} + +/// `current` is the index of one of the `held` files. +fn check_current(current: &Value, held: usize) -> Result<(), String> { + match held { + _ if current.as_u64().is_some_and(|i| i < held as u64) => Ok(()), + 0 => Err("`current` can't be set: no file is queued".into()), + _ => Err(format!("`current` must be the index of a queued file, from 0 to {}", held - 1)), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 700c045d3f..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. @@ -596,7 +599,12 @@ fn with_object_bounds(cx: &ToolContext, walk: impl FnOnce(&mut dyn FnMut(Node pub(crate) fn inside(cx: &ToolContext, r: Rect, ids: Vec) -> Vec { let symbols = cx.doc.symbol_boxes(); let within = |b: Rect| r.min_x() <= b.min_x() && b.max_x() <= r.max_x() && r.min_y() <= b.min_y() && b.max_y() <= r.max_y(); - ids.into_iter().filter(|id| cx.doc.node(*id).and_then(|n| n.geometric_bounds_with(&symbols)).is_some_and(within)).collect() + // Locked or hidden guides, which the marquee leaves out, don't count toward a group's box (#8538). + let measure = |n: &vectorcraft_doc::Node| match n.without_guides().filter(|_| !cx.guides) { + Some(art) => art.geometric_bounds_with(&symbols), + None => n.geometric_bounds_with(&symbols), + }; + ids.into_iter().filter(|id| cx.doc.node(*id).and_then(measure).is_some_and(within)).collect() } /// What of the bounding box is under the pointer. @@ -822,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. @@ -859,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) @@ -891,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![] @@ -942,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(), @@ -1121,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); @@ -1199,7 +1227,7 @@ impl Tool for SelectionTool { if r.width() < Self::drag_threshold(cx) && r.height() < Self::drag_threshold(cx) { return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; } - let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline); + let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline, !cx.guides); let enclosed = marquee_enclosed(cx, enclosed, marquee_direction(cx, start, p, directional_inside)); let ids = if enclosed { inside(cx, r, touched) } else { touched }; let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": json_ids(&ids) })); @@ -1228,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)), @@ -1287,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, @@ -1318,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; } @@ -1380,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)) } @@ -1684,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![]; } @@ -1723,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); @@ -1733,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 a8e1f8acee..5c52201a6f 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1,6 +1,6 @@ use super::*; use crate::testutil::*; -use vectorcraft_doc::Selection; +use vectorcraft_doc::{Document, NodeKind, Selection}; /// While an opacity mask is edited, a press on a selected Shaper original shape moves it, over the /// art the group shows and over a part of the shape the group does not show. A press on an original @@ -146,6 +146,66 @@ fn a_press_where_a_mask_hides_a_selected_object_drags_it() { assert!(a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{a:?}"); } +/// #8538: while guides are locked or hidden (`guides` off), a Selection tool marquee that touches +/// only a guide path in a group selects nothing, so a drag can't move the guide; one that touches +/// the group's other member selects the group. With guides unlocked, the guide takes the group. +#[test] +fn a_marquee_over_a_locked_guide_in_a_group_selects_nothing() { + let mut d = Document::new(800.0, 600.0); + let l = d.layers[0].id; + let (gid, guide_id, art_id) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut guide = vectorcraft_doc::Node::path( + guide_id, + vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 120.0, 120.0)), + vectorcraft_doc::Appearance::default_art(), + ); + if let NodeKind::Path { guide, .. } = &mut guide.kind { + *guide = true; + } + let art = vectorcraft_doc::Node::path( + art_id, + vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 100.0, 320.0, 120.0)), + vectorcraft_doc::Appearance::default_art(), + ); + d.insert(Some(l), 0, vectorcraft_doc::Node::group(gid, vec![std::sync::Arc::new(guide), std::sync::Arc::new(art)])).unwrap(); + let (none, p) = (Selection::default(), paint()); + let marquee = |guides: bool, x0: f64, x1: f64| { + let c = ToolContext { guides, ..cx(&d, &none, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, x0, 50.0)); + t.pointer(&c, &ev(PointerKind::Drag, x1, 110.0)); + let up = t.pointer(&c, &ev(PointerKind::Up, x1, 110.0)); + up.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "select.set" => Some(v["ids"].clone()), + _ => None, + }) + }; + assert_eq!(marquee(false, 90.0, 130.0), Some(json!([])), "locked: only the guide"); + assert_eq!(marquee(false, 290.0, 330.0), Some(json!([gid.0])), "locked: the group's art"); + assert_eq!(marquee(true, 90.0, 130.0), Some(json!([gid.0])), "unlocked: the guide"); +} + +/// #8538: an enclosing marquee measures a group without the locked or hidden guides in it, as the +/// marquee leaves them out: a group whose art lies inside is taken though a guide in it reaches +/// past the marquee. While guides can be picked, the guide counts. +#[test] +fn an_enclosing_marquee_measures_a_group_without_its_locked_guides() { + let mut d = Document::new(800.0, 600.0); + let l = d.layers[0].id; + let (gid, guide_id, art_id) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let square = |id, r| vectorcraft_doc::Node::path(id, vectorcraft_geom::shapes::rectangle(r), vectorcraft_doc::Appearance::default_art()); + let mut guide = square(guide_id, Rect::new(500.0, 100.0, 520.0, 120.0)); + if let NodeKind::Path { guide, .. } = &mut guide.kind { + *guide = true; + } + let art = square(art_id, Rect::new(100.0, 100.0, 120.0, 120.0)); + d.insert(Some(l), 0, vectorcraft_doc::Node::group(gid, vec![std::sync::Arc::new(guide), std::sync::Arc::new(art)])).unwrap(); + let (none, p) = (Selection::default(), paint()); + let r = Rect::new(50.0, 50.0, 200.0, 200.0); + assert_eq!(crate::select::inside(&ToolContext { guides: false, ..cx(&d, &none, &p) }, r, vec![gid]), [gid], "locked or hidden"); + assert!(crate::select::inside(&ToolContext { guides: true, ..cx(&d, &none, &p) }, r, vec![gid]).is_empty(), "shown and unlocked"); +} + /// #955: grabbed by an anchor and dropped near another object's anchor, the anchor lands /// exactly on it with Smart Guides, even where lining the bounds up would leave it beside it. #[test] @@ -2829,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 571a90daa0..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 @@ -1088,6 +1105,21 @@ impl Tool for ShapeTool { } } } + /// The options every shape tool keeps ([`Self::options`]). Any finite angle is taken: it is + /// kept as the same direction from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "sides" | "points" => c::whole(key, v, 3, 1000), + "anchors" => c::whole(key, v, 2, 1000), + "cornerRadius" => c::number(key, v, 0.0, MAX_CORNER_RADIUS), + "starRatio" => c::number(key, v, 0.01, 1.0), + "length" => c::number(key, v, 0.0, 1e6), + "angle" => c::finite(key, v), + "fillLine" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 54ccc4a7f9..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 @@ -1659,6 +1767,18 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() { assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow); } +/// `tool.setOption` takes an ellipse's anchor count from 2 to 1000, as the tool keeps it. +#[test] +fn the_anchor_count_is_checked_against_its_range() { + let t = ShapeTool::new("ellipse"); + for n in [2, 4, 1000] { + assert_eq!(t.check_option("anchors", &json!(n)), Ok(()), "{n}"); + } + for bad in [json!(1), json!(1001), json!(4.5), json!("4")] { + assert_eq!(t.check_option("anchors", &bad), Err("`anchors` must be a whole number from 2 to 1000".into()), "{bad}"); + } +} + /// A drag event to `(x, y)` with Backtick held or not. fn quote_drag(x: f64, y: f64, held: bool) -> PointerEvent { PointerEvent { backquote: held, ..PointerEvent::new(PointerKind::Drag, x, y) } 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/symbolism.rs b/crates/tools/src/symbolism.rs index ba00ec4125..b4dd9e631b 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -222,6 +222,15 @@ impl Tool for SymbolismTool { _ => {} } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, 2.0, 2000.0), + "intensity" | "density" => c::number(key, v, 1.0, 10.0), + "symbol" | "style" => c::string_or_null(key, v), + _ => Err(c::unknown(key)), + } + } } /// Paintbrush: the freehand gesture, painting with the current brush. @@ -293,6 +302,9 @@ impl Tool for BrushPaintTool { self.inner.set_option(key, v); } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "brush" { crate::option_check::string_or_null(key, v) } else { self.inner.check_option(key, v) } + } fn wants_samples(&self) -> bool { self.inner.wants_samples() } diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 763325f90e..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; @@ -137,6 +140,15 @@ fn text_hash(s: &str) -> u64 { /// The edited text's layout, keyed by [`vectorcraft_text::layout_inputs`] and the text. type CachedLayout = ((u64, TextObject), Arc); +/// The layouts of the frames other than the edited one that the overlays draw (the ports of the +/// selected area type and type on a path, the other frames of a selected story), by frame, each +/// kept with the layout inputs and the text it was made from ([`TypeTool::frame_layout`]). +type FrameLayouts = std::collections::HashMap; + +/// The most other frames' layouts [`TypeTool::frames`] keeps: every port drawn ([`PORTS_MAX`]) +/// and a long story's frames. The frames an overlays call draws past it are laid out on each call. +const FRAME_LAYOUTS_MAX: usize = 2_048; + /// Process-global Type-tool edit-session counter: the IME target's replacement epoch. /// /// A per-tool counter restarts at zero when the tool is recreated (a document switch, File › @@ -219,7 +231,12 @@ 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. + frames: Mutex, } struct BeforePress { @@ -296,6 +313,28 @@ impl TypeTool { l } + /// Layout of `t`, frame `id`, for an overlays call that draws a frame other than the edited + /// one: the layout kept in `now` or `was` for `id` when it was made from the layout inputs + /// `fonts` and the same text, otherwise a new one. It is kept in `now` either way while `now` + /// holds fewer than [`FRAME_LAYOUTS_MAX`]. + fn frame_layout(now: &mut FrameLayouts, was: &mut FrameLayouts, fonts: u64, id: NodeId, t: &TextObject) -> Arc { + if let Some(((g, k), l)) = now.get(&id) + && *g == fonts + && k == t + { + return l.clone(); + } + let kept = match was.remove(&id) { + Some(((g, k), l)) if g == fonts && &k == t => ((g, k), l), + _ => ((fonts, t.clone()), Arc::new(vectorcraft_text::layout(FontDb::global(), t))), + }; + let l = kept.1.clone(); + if now.len() < FRAME_LAYOUTS_MAX { + now.insert(id, kept); + } + l + } + /// The edited text used to find word and paragraph boundaries for selection: the typing session's /// runs, or the document's current text when there is no live session or it has gone stale. fn plain(&self, cx: &ToolContext) -> String { @@ -781,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 94063166bc..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) { @@ -1636,10 +1638,282 @@ fn the_edited_types_ports_follow_the_limit_too() { tool.start_editing(id, 0); let boxes = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [255, 255, 255, 255], .. })).count(); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 2 * PORTS_MAX, "at the limit, the edited one's included"); + assert_eq!(kept_frames(&tool), PORTS_MAX - 1, "the other frames' layouts are kept"); let copy = d.alloc_id(); d.insert(Some(l), 1, Node::new(copy, node.kind.clone())).unwrap(); sel.add(copy); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 0, "past it, not even the edited one's"); + assert_eq!(kept_frames(&tool), 0, "no ports drawn, no layouts kept"); +} + +/// How many other frames' layouts the Type tool keeps between overlays calls. +fn kept_frames(tool: &TypeTool) -> usize { + tool.frames.lock().unwrap().len() +} + +/// The value `f` returns, and how many layouts this thread started while it ran. +fn counted(f: impl FnOnce() -> T) -> (T, u64) { + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let v = f(); + (v, vectorcraft_text::test_fonts::layouts_on_this_thread() - before) +} + +/// A document with area type frames of `texts` (each 120 × 40 pt, one under the other) and their ids. +fn area_frames(texts: &[&str]) -> (Document, Vec) { + let mut d = Document::new(500.0, 2000.0); + let l = d.layers[0].id; + let mut ids = Vec::new(); + for (i, s) in texts.iter().enumerate() { + let id = d.alloc_id(); + let mut t = TextObject::point(Point::new(50.0, 50.0 + 60.0 * i as f64), s, CharStyle::default()); + t.kind = area_kind(120.0, 40.0); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + ids.push(id); + } + (d, ids) +} + +/// Area type in a `w` × `h` pt frame. +fn area_kind(w: f64, h: f64) -> TextKind { + TextKind::Area { frame: vectorcraft_geom::PathData::from_bezpath(&Rect::new(0.0, 0.0, w, h).to_path(0.1)) } +} + +fn text_mut(d: &mut Document, id: NodeId) -> &mut TextObject { + match &mut d.node_mut(id).unwrap().kind { + NodeKind::Text(t) => t, + _ => panic!("not text"), + } +} + +const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hundred and twenty by forty points."; + +/// The Type tools draw the ports of several different selected frames, with and without one of +/// them being edited, without laying any of them out again on the next frame, and draw the same +/// 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()); + let c = cx(&d, &sel, &p); + let mut probe = Vec::new(); + push_port(&mut probe, Point::ZERO, PortState::Overflow, [0, 0, 0], 1.0); + let Some(Overlay::Line { color: red, .. }) = probe.last().cloned() else { panic!("the red plus is drawn with lines") }; + let red_plus = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Line { color, .. } if *color == red)).count(); + for editing in [None, Some(ids[0])] { + let mut tool = TypeTool::new("areaType"); + if let Some(id) = editing { + tool.start_editing(id, 0); + } + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0, "{editing:?}: the first frame lays the frames out"); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "{editing:?}: the next frame lays none out again"); + assert_eq!(first, second, "{editing:?}"); + let mut fresh = TypeTool::new("areaType"); + if let Some(id) = editing { + fresh.start_editing(id, 0); + } + assert_eq!(second, fresh.overlays(&c), "{editing:?}: what laying out afresh draws"); + assert!(red_plus(&second) > 0, "{editing:?}: the overflowing frame's out port shows its red plus"); + } +} + +/// After Select All in threaded text, the story's other frames are highlighted without laying them +/// 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()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + assert_eq!(tool.story_others(&c).len(), 3); + let highlights = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [60, 120, 255, 90], .. })).count(); + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "the story's other frames are not laid out again"); + assert_eq!(first, second); + let mut fresh = TypeTool::new("areaType"); + fresh.start_editing(ids[0], 0); + fresh.set_option("selectAll", &story); + assert_eq!(second, fresh.overlays(&c), "what laying out afresh draws"); + assert!(highlights(&second) >= 4, "every frame's text is highlighted: {}", highlights(&second)); +} + +/// A kept layout is used only while its frame's text object is unchanged: editing the text, +/// changing the frame and undoing both lay out just the frames that changed, a frame that is no +/// 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()); + let mut tool = TypeTool::new("areaType"); + let fresh = |d: &Document, sel: &Selection| TypeTool::new("areaType").overlays(&cx(d, sel, &p)); + tool.overlays(&cx(&d, &sel, &p)); + let start = d.clone(); + // Edit the text of one frame. + text_mut(&mut d, ids[1]).runs[0].text = OVERFLOWS.into(); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the edited frame"); + assert_eq!(o, fresh(&d, &sel)); + // Make another frame tall enough for its text. + text_mut(&mut d, ids[3]).kind = area_kind(120.0, 400.0); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the changed frame"); + assert_eq!(o, fresh(&d, &sel)); + // Undo puts both back. + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 2, "the two frames undo changed"); + assert_eq!(o, fresh(&start, &sel)); + // A smaller selection keeps only its frames; the others are laid out again when selected again. + let mut one = Selection::default(); + one.set([ids[0]]); + assert_eq!(counted(|| tool.overlays(&cx(&start, &one, &p))).1, 0); + assert_eq!(kept_frames(&tool), 1); + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 3); + assert_eq!(o, fresh(&start, &sel)); + tool.deactivate(&cx(&start, &sel, &p)); + assert_eq!(kept_frames(&tool), 0, "another tool chosen"); +} + +/// A story of more frames than [`FRAME_LAYOUTS_MAX`] keeps that many layouts, lays the rest out on +/// 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()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + let first = tool.overlays(&c); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 2, "the two other frames past the limit"); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + assert_eq!(first, second); +} + +#[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") { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "text::tests::frame_layouts_follow_fonts_and_hyphenation_exceptions", "--nocapture", "--test-threads=1"]) + .env("VECTORCRAFT_FONT_CACHE_TEST_CHILD", "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated font cache test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let (mut d, ids) = area_frames(&["One", "Two", "Three ", "four"]); + d.text_threads.push(vec![ids[2], ids[3]]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0], ids[1], ids[2]]); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[2], 0); + tool.set_option("selectAll", &json!({ "story": [ids[2].0, ids[3].0] })); + tool.overlays(&c); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + // Two selected frames, the story's other frame and the edited one. + let font = vectorcraft_text::test_fonts::variable_font().unwrap(); + assert!(FontDb::global().add_font(font) > 0, "the test font is new to this process"); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "a font added after the layouts refreshes them"); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + vectorcraft_text::set_hyphenation_exceptions(&vectorcraft_text::hyphenation_exceptions()); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "new hyphenation exceptions refresh them"); +} + +/// Times the Type tool's overlays on 200 selected area type frames of about 400 characters, one of +/// them edited, and on a 5-frame story after Select All, laying every frame out on each call as the +/// tool did before it kept their layouts (base) against keeping them (kept). Run with +/// `cargo test --release -p vectorcraft-tools --lib type_overlays_timing -- --ignored --nocapture`. +#[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(); + let (mut d, ids) = area_frames(&texts.iter().map(String::as_str).collect::>()); + for id in &ids { + text_mut(&mut d, *id).kind = area_kind(200.0, 200.0); + } + let story: Vec = ids[..5].to_vec(); + d.text_threads.push(story.clone()); + let p = paint(); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut first = Selection::default(); + first.set([ids[0]]); + // Before, the selected frames' layouts replaced the edited one's single kept layout; with only + // the edited frame selected, it stayed. + let cases = [("200 selected frames, one edited", &all, None, true), ("5-frame story, Select All", &first, Some(story), false)]; + for (name, sel, story, evicted) in cases { + let c = cx(&d, sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + if let Some(s) = &story { + tool.set_option("selectAll", &json!({ "story": s.iter().map(|id| id.0).collect::>() })); + } + let expected = tool.overlays(&c); + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + let (_, before) = counted(|| tool.overlays(&c)); + let (_, after) = counted(|| tool.overlays(&c)); + println!("{name}: {before} layouts per call before, {after} after"); + let calls = 20; + let (mut base, mut kept) = (Vec::new(), Vec::new()); + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..calls { + // Before: the other frames were laid out on every call. + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + assert_eq!(tool.overlays(&c), expected); + } + base.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + let start = Instant::now(); + for _ in 0..calls { + assert_eq!(tool.overlays(&c), expected); + } + kept.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("{name}: base runs {base:.3?} ms per call, kept runs {kept:.3?} ms per call"); + println!("{name}: median base {:.3} ms, kept {:.3} ms per call", median(&mut base), median(&mut kept)); + } } /// Type on a path has its in port just before its start bracket and its out port just past its @@ -1897,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 e18754f0ca..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,8 +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 @@ -537,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)) = ( @@ -609,6 +628,25 @@ impl Tool for TypeTool { _ => {} } } + /// The calls [`Self::set_option`] takes: `commitTyping`, `endTyping`, `selectAll` and + /// `stopEditing` take any value, the others the shapes they read. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + let index = |a: &str, b: &str| v.get(a).or_else(|| v.get(b)).and_then(Value::as_u64).is_some(); + let ok = match key { + "textSelection" => index("editing", "id") && index("anchor", "start") && index("caret", "end"), + "select" => index("start", "start") && index("end", "end"), + "prevTool" | "previousTool" => return crate::option_check::string_or_null(key, v), + "copy" => serde_json::from_value::>(v.clone()).is_ok(), + "commitTyping" | "endTyping" | "selectAll" | "stopEditing" => true, + _ => return Err(crate::option_check::unknown(key)), + }; + let shape = match key { + "textSelection" => "{editing, anchor, caret} with whole numbers", + "select" => "{start, end} with whole numbers", + _ => "a list of text runs", + }; + if ok { Ok(()) } else { Err(format!("`{key}` must be {shape}")) } + } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); if let (Some((_, s)), Some(d)) = (self.press, self.drag) { @@ -633,13 +671,17 @@ impl Tool for TypeTool { o.push(Overlay::Measure { p: d, text: cx.size_label(size.width, size.height) }); } } + // The other frames this call draws keep their layouts for the next call; the rest are dropped. + let fonts = vectorcraft_text::layout_inputs(); + let mut now = self.frames.lock().unwrap_or_else(|e| e.into_inner()); + let mut was = std::mem::take(&mut *now); // The ports of selected area type and type on a path, as many as show ([`PORTS_MAX`]), the // edited one's included. let shown = ports_shown(cx.doc, &cx.selection.objects); if shown { for id in cx.selection.objects.iter().filter(|id| Some(**id) != self.editing) { if let Some(t) = ported(cx.doc, *id) { - let lay = self.layout(t); + let lay = Self::frame_layout(&mut now, &mut was, fonts, *id, t); ports(cx, *id, t, lay.overflow, &mut o); } } @@ -688,7 +730,7 @@ impl Tool for TypeTool { if self.preedit.is_none() { for f in self.story_others(cx) { let Some(other) = Self::text(cx, f) else { continue }; - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), other); + let lay = Self::frame_layout(&mut now, &mut was, fonts, f, other); for q in vectorcraft_text::selection_quads(&lay, 0, edit::runs_len(&other.runs)) { o.push(Overlay::Highlight { quad: q.map(|p| other.xf * p), color: [60, 120, 255, 90] }); } 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 5af642c44b..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)] { @@ -726,6 +733,18 @@ impl Tool for ArtboardTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "active" if value.as_u64().is_some() => Ok(()), + "active" => Err("`active` must be an artboard index: a whole number from 0".into()), + "selected" if value.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|i| i.as_u64().is_some())) => Ok(()), + "selected" => Err("`selected` must be a list of artboard indexes, the active one first".into()), + "moveArt" | "scaleArt" | "suppressFitClick" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + /// A drag is moving or resizing artboards (Artboard Options › Update While Dragging reads it). fn transforming(&self) -> bool { matches!(self.drag, Some(Drag::Move { began: true, .. } | Drag::Resize { began: true, .. })) 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/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index eb1b8b3895..7b91731691 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -593,6 +593,16 @@ impl Tool for EyedropperTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "stop" => c::string_or_null(key, value), + "brushKeyColor" => c::boolean(key, value), + "textSelection" => self.text_selection.check_option(key, value), + _ => Err(c::unknown(key)), + } + } + /// Drop the range when its text is removed or no longer selected. fn after_command(&mut self, cx: &ToolContext) -> Vec { self.text_selection.after_command(cx) diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 1583584940..6b7f213469 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -237,7 +237,15 @@ impl FreeTransformTool { self.measure = cx.transform_tools_guides.then(|| (p, cx.size_label(nr.width(), nr.height()))); bx.conjugate(a) } - Op::Shear(h) => bx.conjugate(shear_for_side(bx.rect, h, local, m.alt)), + Op::Shear(h) => { + let a = shear_for_side(bx.rect, h, local, m.alt); + // The shear's slope, read from the matrix the preview applies, labeled with the + // angle the Shear tool shows for the same slant. + let [_, vertical, horizontal, ..] = a.as_coeffs(); + let k = if matches!(h, Handle::Top | Handle::Bottom) { horizontal } else { vertical }; + self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", 0.0 - k.atan().to_degrees()))); + bx.conjugate(a) + } Op::Rotate => { let (a, deg) = rotate_for_drag(bx.center(), d.start, p, shift); self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", -deg))); @@ -379,6 +387,15 @@ impl Tool for FreeTransformTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "mode" => c::one_of(key, value, &["free", "perspective", "distort", "freeDistort"]), + "constrain" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.quad = None; self.guides.clear(); @@ -723,4 +740,63 @@ mod tests { t.pointer(&cx(false), &ev(PointerKind::Drag, 220.0, 230.0)); assert!(t.overlays(&cx(false)).iter().all(|o| !matches!(o, Overlay::Measure { .. }))); } + + /// The label a drag shows next to the pointer, and where. + fn shown_measure(t: &FreeTransformTool, cx: &ToolContext) -> Option<(Point, String)> { + t.overlays(cx).into_iter().find_map(|o| if let Overlay::Measure { p, text } = o { Some((p, text)) } else { None }) + } + + /// With Smart Guides' Transform Tools on, a Cmd side-handle shear shows its angle next to the + /// pointer, with the Shear tool's sign: the top side moved right and the right side moved down + /// by 20 pt on the 100 pt square slant 11.3° either way. Alt shears about the center. + #[test] + fn shear_drag_shows_its_angle_with_transform_tools_guides() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = |on: bool| ToolContext { transform_tools_guides: on, ..cx(&d, &s, &p) }; + let cmd = Mods { cmd: true, ..Default::default() }; + let shear = |c: &ToolContext, from: (f64, f64), to: (f64, f64), m: Mods| { + let mut t = FreeTransformTool::default(); + t.pointer(c, &ev(PointerKind::Down, from.0, from.1).with_mods(m)); + let a = t.pointer(c, &ev(PointerKind::Drag, to.0, to.1).with_mods(m)); + assert_eq!(a[0], Action::Begin("Shear".into())); + let shown = shown_measure(&t, c); + assert_eq!(t.pointer(c, &ev(PointerKind::Up, to.0, to.1).with_mods(m)), vec![Action::Commit]); + assert_eq!(shown_measure(&t, c), None, "the label goes with the drag"); + shown + }; + let on = cx(true); + let off = Vec2::new(on.tol(12.0), on.tol(12.0)); + assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), cmd), Some((Point::new(170.0, 100.0) + off, "11.3°".into()))); + assert_eq!(shear(&on, (200.0, 150.0), (200.0, 170.0), cmd), Some((Point::new(200.0, 170.0) + off, "-11.3°".into()))); + // About the center the lever is half as long: atan(20 / 50). + let alt = Mods { alt: true, ..cmd }; + assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), alt).map(|m| m.1), Some("21.8°".into())); + // A drag straight away from the side, at right angles to it, shears nothing. + assert_eq!(shear(&on, (150.0, 100.0), (150.0, 90.0), cmd).map(|m| m.1), Some("0.0°".into())); + assert_eq!(shear(&cx(false), (150.0, 100.0), (170.0, 100.0), cmd), None); + } + + /// A handle drag that turns into a shear, and back into a scale, labels only what it does now. + #[test] + fn a_handle_drag_that_changes_operation_relabels_it() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = ToolContext { transform_tools_guides: true, ..cx(&d, &s, &p) }; + let cmd = Mods { cmd: true, ..Default::default() }; + let mut t = FreeTransformTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0)); + let size = cx.size_label(100.0, 110.0); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size.clone())); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 170.0, 100.0).with_mods(cmd)); + assert_eq!(a[..2], [Action::Cancel, Action::Begin("Shear".into())]); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some("11.3°".into())); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0)); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size)); + } } diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 16a1b93a8a..339984e9a1 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -432,6 +432,15 @@ impl Tool for TransformTool { } } + /// `origin` is `[x, y]`, or null to clear it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key != "origin" { + return Err(crate::option_check::unknown(key)); + } + let point = value.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|n| n.as_f64().is_some_and(f64::is_finite))); + if point || value.is_null() { Ok(()) } else { Err("`origin` must be [x, y] with finite numbers, or null".into()) } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } } diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 5b37b52abf..3f4d2e4551 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -4,7 +4,8 @@ //! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that //! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu //! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each -//! with a Select button; each document's list is kept until that document changes. +//! with a Select button; each document's list is kept until that document changes. Its Fold Preview +//! button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`). use std::collections::HashMap; use std::sync::{Arc, Weak}; @@ -26,6 +27,8 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that shows the Fold Preview window. +pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. pub const ROLES: &[(&str, &str)] = &[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")]; @@ -47,6 +50,8 @@ pub fn menu() -> Vec { make("Make Perforation Line", "perforation"), Item::Sep, Item::Cmd("Check Fold Lines", CHECK, Value::Null), + Item::Sep, + Item::Cmd("Fold Preview", PREVIEW, json!({})), ] } @@ -160,6 +165,11 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::flat_button(ui, tl!("Check"), width).clicked() { run_check(app, ui.ctx(), json!({})); } + if widgets::flat_button(ui, tl!("Fold Preview"), width).clicked() + && let Err(e) = app.run(PREVIEW, json!({})) + { + app.status(e); + } let Some(checked) = last_check(app, ui.ctx()) else { return }; ui.add_space(4.0); dim_label(ui, &crate::i18n::msg(&checked.summary())); @@ -285,5 +295,7 @@ pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +pub mod preview; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs new file mode 100644 index 0000000000..97a8ebd988 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -0,0 +1,705 @@ +//! The Fold Preview window: the document's blank folded into its 3D shape +//! ([`vectorcraft_three_d::fold::fold`]), with the printed art on the outside of each panel and the +//! board's inside color on the back, drawn by [`vectorcraft_three_d::fold::raster::render`]. +//! +//! The window folds the blank that the document's shown fold lines make, about its largest panel +//! or the panel the user double-clicked. Its print is a raster of the document with the fold lines +//! and the layers that do not print left out ([`vectorcraft_engine::cmd::print_hidden`]), rendered +//! once per document revision, off the UI thread on native builds ([`crate::thumb_worker`]), and +//! sampled through each panel's projective map when the fold, the view or the print changes. Dragging turns the view, a Shift-drag +//! keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a +//! panel makes it the base, and the arrow keys turn the view by 5° when it has the keyboard focus. +//! The settings live in `UiState::fold_preview` (`ui.inspect`); `ui.foldPreview` sets them. + +use std::sync::Arc; + +use egui::{Color32, Rect, Sense, Ui, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect as DRect}; +use vectorcraft_three_d::fold::raster::{self, Camera, Image, MAX_PIXELS, MAX_SIDE, Print}; +use vectorcraft_three_d::fold::{Blank, Folded, fold, pick}; + +use crate::VectorcraftApp; +use crate::thumb_worker::{Settle, ThumbWorker}; +use crate::widgets::{self, dim_label}; + +/// The window's id (`window.panel {panel: "foldPreview"}`). +pub const ID: &str = "foldPreview"; + +/// The view presets: label, id, the turn about x (the top toward the viewer) and about y (the +/// right side toward the viewer), in degrees. +pub const VIEWS: [(&str, &str, f64, f64); 7] = [ + ("Front", "front", 0.0, 0.0), + ("Back", "back", 0.0, 180.0), + ("Left", "left", 0.0, -90.0), + ("Right", "right", 0.0, 90.0), + ("Top", "top", 90.0, 0.0), + ("Bottom", "bottom", -90.0, 0.0), + ("Three-Quarter", "threeQuarter", 25.0, 35.0), +]; + +/// The tolerance the window folds with (points), as Check Fold Lines' default. +const TOLERANCE: f64 = 0.1; +/// The share of the view's shorter side the folded blank fills at a zoom of 1. +const FIT: f64 = 0.45; +/// The print raster's longest side, in pixels, and the fewest pixels it gives a point. +const PRINT_SIDE: f64 = 2048.0; +/// Degrees the view turns for each point dragged, and for each arrow key press. +const DRAG_TURN: f64 = 0.5; +const KEY_TURN: f64 = 5.0; + +/// The window's settings (kept with the UI state). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Settings { + /// How far the blank is folded: 0 flat, 1 every hinge at its angle. + pub amount: f64, + /// The view's turn, in degrees (see [`VIEWS`]). + pub rotate_x: f64, + pub rotate_y: f64, + /// The zoom: 1 fits the folded blank in the view. + pub zoom: f64, + /// How far the view is moved, in points. + pub pan: [f64; 2], + /// The field of view in degrees; 0 for none. + pub perspective: f64, + /// The board's inside color: `#rrggbb`, the name of a swatch, or empty for white. + pub inside: String, + /// Draw the fold lines on the print. + pub show_fold_lines: bool, + /// The base panel: the one under this point (document coordinates); the largest when `None`. + pub base: Option<[f64; 2]>, +} + +impl Default for Settings { + fn default() -> Self { + let (_, _, rotate_x, rotate_y) = VIEWS[6]; + Self { + amount: 1.0, + rotate_x, + rotate_y, + zoom: 1.0, + pan: [0.0; 2], + perspective: 0.0, + inside: String::new(), + show_fold_lines: false, + base: None, + } + } +} + +impl Settings { + /// The view preset these settings show, if any. + fn view(&self) -> Option<&'static (&'static str, &'static str, f64, f64)> { + VIEWS.iter().find(|v| (v.2 - self.rotate_x).abs() < 1e-9 && (v.3 - self.rotate_y).abs() < 1e-9) + } + + /// These settings with every value in the range `ui.foldPreview` allows: saved UI state is read + /// as it was stored. A value that is not a number takes its default. + fn clamped(mut self) -> Self { + let within = |v: f64, lo: f64, hi: f64, or: f64| if v.is_finite() { v.clamp(lo, hi) } else { or }; + let turn = |v: f64| if (-180.0..=180.0).contains(&v) { v } else { wrapped(v) }; + let fresh = Settings::default(); + self.amount = within(self.amount, 0.0, 1.0, fresh.amount); + self.zoom = within(self.zoom, 0.1, 8.0, fresh.zoom); + self.perspective = within(self.perspective, 0.0, 160.0, fresh.perspective); + (self.rotate_x, self.rotate_y) = (turn(self.rotate_x), turn(self.rotate_y)); + self.pan = self.pan.map(|v| if v.is_finite() { v } else { 0.0 }); + self.base = self.base.filter(|b| b.iter().all(|v| v.is_finite())); + self + } +} + +/// `angle` (degrees) brought into -180 to 180. +fn wrapped(angle: f64) -> f64 { + let a = (angle + 180.0).rem_euclid(360.0) - 180.0; + if a.is_finite() { a } else { 0.0 } +} + +/// What the print raster shows: the document, its revision, whether the fold lines are drawn, and +/// the region and size. +#[derive(Clone, Copy, Debug, PartialEq)] +struct PrintKey { + uid: u64, + revision: u64, + fold_lines: bool, + region: [u64; 4], + width: u32, + height: u32, +} + +/// The last frame drawn: its size in pixels and how long the fold and the drawing took (ms). +#[derive(Clone, Copy, Debug, Default)] +struct Frame { + width: u32, + height: u32, + fold_ms: f64, + draw_ms: f64, +} + +/// A document's blanks and whether its fold lines have an error, by (uid, revision). +type Blanks = ((u64, u64), Arc>, bool); + +/// What a fold folds: the document (uid, revision), the blank, the base panel and the amount's bits. +type FoldKey = (u64, u64, usize, usize, u64); + +/// What the last image shows: the fold, the camera, the inside color and the print. +#[derive(Clone, Copy, Debug, PartialEq)] +struct DrawKey { + fold: FoldKey, + camera: Camera, + inside: [u8; 4], + print: Option, +} + +#[derive(Default)] +struct Cache { + blanks: Option, + /// The last fold, what it folds and how long it took (ms). + folded: Option<(FoldKey, Arc, f64)>, + /// What the texture shows. + drawn: Option, + /// Folds worked out and images rendered (tests count them). + folds: u64, + renders: u64, + /// The print shown and what it shows. + print: Option<(PrintKey, Arc)>, + /// Renders the print off the UI thread (None: on this thread). + worker: Option>, + worker_started: bool, + pending: Option, + settle: Settle, + tex: Option, + /// The last frame's image, for double-click picking, and the screen rect it filled. + image: Option<(Image, Rect)>, + frame: Option, + /// Prints rendered (tests count them). + prints: u64, +} + +thread_local! { + static CACHE: crate::graphics::TexCache = crate::graphics::TexCache::default(); + static RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); +} + +/// The board's inside color (straight RGBA) for `inside`: white when it is empty, a swatch of `d` +/// with a plain color, or else `#rrggbb`; `None` for anything else. +fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { + if inside.is_empty() { + return Some([255; 4]); + } + match d.swatch(inside).map(|s| &s.paint) { + Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), + _ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)), + _ => None, + } +} + +/// The document rect a print of `blank` covers: its panels' bounds, with a point to spare. +fn print_region(blank: &Blank) -> Option { + let r = blank.panels.iter().filter_map(|p| p.outline.bounds()).reduce(|a, b| a.union(b))?; + let r = r.inflate(1.0, 1.0); + (r.width() > 0.0 && r.height() > 0.0 && r.is_finite()).then_some(r) +} + +/// The pixel size of the print of `region`: its longest side [`PRINT_SIDE`]. +fn print_size(region: DRect) -> (u32, u32, f64) { + let scale = PRINT_SIDE / region.width().max(region.height()); + let side = |len: f64| ((len * scale).ceil() as u32).clamp(1, MAX_SIDE); + (side(region.width()), side(region.height()), scale) +} + +impl Cache { + /// The blanks of document `uid` at `revision`, worked out again only when it changed. + fn blanks(&mut self, uid: u64, revision: u64, d: &vectorcraft_engine::doc::Document) -> (Arc>, bool) { + if let Some((key, blanks, errors)) = &self.blanks + && *key == (uid, revision) + { + return (blanks.clone(), *errors); + } + let (blanks, issues) = vectorcraft_engine::cmd::fold_source(d); + let errors = issues.iter().any(|i| i.code.is_error()); + let blanks = Arc::new(blanks); + self.blanks = Some(((uid, revision), blanks.clone(), errors)); + (blanks, errors) + } + + /// `blank` folded about `panel` by `amount` (what `key` names), worked out again only when the + /// key changed, and how long that took (ms). + fn fold(&mut self, key: FoldKey, blank: &Blank, panel: usize, amount: f64) -> Option<(Arc, f64)> { + if let Some((k, f, ms)) = &self.folded + && *k == key + { + return Some((f.clone(), *ms)); + } + let t0 = crate::now_ms(); + let f = Arc::new(fold(blank, Some(panel), amount, TOLERANCE)?); + let ms = crate::now_ms() - t0; + self.folded = Some((key, f.clone(), ms)); + self.folds += 1; + Some((f, ms)) + } + + /// Bring the print up to `key`: on the worker when there is one, else here, and not before the + /// document has settled unless there is no print of it yet. + fn update_print(&mut self, ctx: &egui::Context, doc: &Arc, key: PrintKey, region: DRect, scale: f64) { + if !self.worker_started { + self.worker_started = true; + self.worker = ThumbWorker::spawn(ctx, "fold-preview"); + } + let done = match self.worker.as_ref().map(ThumbWorker::poll) { + Some(Some(done)) => done, + Some(None) => { + (self.worker, self.pending) = (None, None); + vec![] + } + None => vec![], + }; + for d in done { + if self.pending == Some(d.key) { + self.pending = None; + } + if let Some(img) = d.img { + self.keep_print(d.key, img); + } + } + let shown = self.print.as_ref().map(|(k, _)| *k); + if shown == Some(key) || self.pending == Some(key) { + return; + } + let have = shown.is_some_and(|k| k.uid == key.uid); + if have && !self.settle.settled(ctx, key.uid, key.revision, ctx.input(|i| i.time)) { + return; + } + let opts = vectorcraft_render::RenderOptions { + skip_templates: true, + image_mips: true, + hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines), + ..Default::default() + }; + if let Some(w) = &self.worker { + let (doc, opts) = (doc.clone(), opts.clone()); + if w.submit((), key, Box::new(move |r| Some(r.render_region_with(&doc, region, scale, &opts)))) { + self.pending = Some(key); + return; + } + self.worker = None; + } + let img = RENDERER.with(|r| r.borrow_mut().render_region_with(doc, region, scale, &opts)); + self.keep_print(key, img); + } + + /// The print to draw for `want`: the one shown when it is of the same document, blank region and + /// Show Fold Lines setting (an older revision while the new one renders), else none. + fn print_for(&self, want: &PrintKey) -> Option<(PrintKey, Arc)> { + let same = |k: &PrintKey| (k.uid, k.fold_lines, k.region) == (want.uid, want.fold_lines, want.region); + self.print.as_ref().filter(|(k, _)| same(k)).map(|(k, p)| (*k, p.clone())) + } + + fn keep_print(&mut self, key: PrintKey, img: vectorcraft_render::Rendered) { + let region = + DRect::new(f64::from_bits(key.region[0]), f64::from_bits(key.region[1]), f64::from_bits(key.region[2]), f64::from_bits(key.region[3])); + if let Some(print) = Print::new(region, img.width, img.height, img.pixels) { + self.print = Some((key, Arc::new(print))); + self.prints += 1; + } + } +} + +/// `ui.foldPreview {amount?, view?, rotateX?, rotateY?, zoom?, perspective?, inside?, +/// showFoldLines?, base?}`: set the window's settings, show it, and answer with them and the last +/// frame's size and times. A value of the wrong kind or out of range is an error, and nothing is +/// set. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { + let mut set = app.ui.fold_preview.clone(); + let number = |key: &str, lo: f64, hi: f64| -> Result, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(n) if (lo..=hi).contains(&n) => Ok(Some(n)), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + }, + } + }; + if let Some(a) = number("amount", 0.0, 1.0)? { + set.amount = a; + } + match p.get("view") { + None | Some(Value::Null) => {} + Some(v) => { + let (_, _, x, y) = v + .as_str() + .and_then(|v| VIEWS.iter().find(|view| view.1 == v)) + .ok_or_else(|| format!("`view` must be one of {}", VIEWS.iter().map(|v| v.1).collect::>().join(", ")))?; + (set.rotate_x, set.rotate_y) = (*x, *y); + } + } + if let Some(x) = number("rotateX", -180.0, 180.0)? { + set.rotate_x = x; + } + if let Some(y) = number("rotateY", -180.0, 180.0)? { + set.rotate_y = y; + } + if let Some(z) = number("zoom", 0.1, 8.0)? { + set.zoom = z; + } + if let Some(v) = number("perspective", 0.0, 160.0)? { + set.perspective = v; + } + match p.get("inside") { + None | Some(Value::Null) => {} + Some(v) => { + let inside = v.as_str().filter(|inside| { + inside.is_empty() + || app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() + || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()) + }); + let Some(inside) = inside else { + return Err(format!("`inside` must be #rrggbb, the name of a swatch with a plain color, or empty for white, not {v}")); + }; + set.inside = inside.to_string(); + } + } + match p.get("showFoldLines") { + None | Some(Value::Null) => {} + Some(v) => set.show_fold_lines = v.as_bool().ok_or("`showFoldLines` must be true or false")?, + } + match p.get("base") { + None => {} + Some(Value::Null) => set.base = None, + Some(v) => { + let a = v.as_array().filter(|a| a.len() == 2); + let xy: Option> = a.map(|a| a.iter().filter_map(Value::as_f64).filter(|n| n.is_finite()).collect()); + let Some(&[x, y]) = xy.as_deref() else { return Err("`base` must be a point: [x, y], or null".into()) }; + let blanks = app.session.active().map(|st| vectorcraft_engine::cmd::fold_source(&st.doc).0).unwrap_or_default(); + if pick(&blanks, Some(Point::new(x, y))).is_none() { + return Err("`base` is in no panel".into()); + } + set.base = Some([x, y]); + } + } + if p.get("view").is_some_and(|v| !v.is_null()) || p.get("zoom").is_some_and(|v| !v.is_null()) { + set.pan = [0.0; 2]; + } + app.ui.fold_preview = set; + crate::panel_docking::reveal_panel(app, ID)?; + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + Ok(state(app)) +} + +/// The window's settings and the last frame's size and times. +fn state(app: &VectorcraftApp) -> Value { + let frame = CACHE.with(|c| c.borrow().frame); + let mut out = serde_json::to_value(&app.ui.fold_preview).unwrap_or_default(); + if let Some(o) = out.as_object_mut() { + o.insert( + "frame".into(), + frame.map_or(Value::Null, |f| json!({"width": f.width, "height": f.height, "foldMs": f.fold_ms, "drawMs": f.draw_ms})), + ); + } + out +} + +/// The toolbar: the view presets, Perspective, Inside, Show Fold Lines and Reset. +fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) { + ui.horizontal_wrapped(|ui| { + let labels: Vec<&str> = VIEWS.iter().map(|v| v.0).collect(); + let current = set.view().map_or("", |v| v.0); + if let Some(i) = widgets::dropdown_named(ui, "fold-preview-view", Some(tl!("View")), current, &labels, 120.0) + && let Some(&(_, _, x, y)) = VIEWS.get(i) + { + (set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]); + } + let swatches: Vec = app.session.active().map_or_else(Vec::new, |st| { + st.doc.swatches.iter().filter(|s| matches!(s.paint, vectorcraft_color::Paint::Solid { .. })).map(|s| s.name.clone()).collect() + }); + let mut names: Vec<&str> = vec![tl!("White")]; + names.extend(swatches.iter().map(String::as_str)); + let shown = if set.inside.is_empty() { tl!("White") } else { set.inside.as_str() }; + ui.label(tl!("Inside")); + if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) { + set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_default(); + } + if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) { + set.show_fold_lines = !set.show_fold_lines; + } + if widgets::flat_button_fit(ui, tl!("Reset"), 48.0).clicked() { + let fresh = Settings::default(); + (set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective) = (fresh.rotate_x, fresh.rotate_y, 1.0, [0.0; 2], 0.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Perspective")); + widgets::slider(ui, egui::Slider::new(&mut set.perspective, 0.0..=160.0).suffix("°").fixed_decimals(0)); + }); +} + +/// The Fold and Zoom sliders. +fn sliders(ui: &mut Ui, set: &mut Settings) { + ui.horizontal(|ui| { + ui.label(tl!("Fold")); + let mut percent = set.amount * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 0.0..=100.0).suffix("%").fixed_decimals(0)).changed() { + set.amount = (percent / 100.0).clamp(0.0, 1.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Zoom")); + let mut percent = set.zoom * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 10.0..=800.0).suffix("%").fixed_decimals(0).logarithmic(true)).changed() { + set.zoom = (percent / 100.0).clamp(0.1, 8.0); + } + }); +} + +/// Turns, moves and zooms the view with the pointer, the wheel and the arrow keys, and picks the +/// base panel of `blank` (the blank `key` folds) on a double-click. +fn interact(ui: &Ui, response: &egui::Response, set: &mut Settings, blank: Option<(&Blank, FoldKey)>) { + if response.clicked() || response.drag_started() { + response.request_focus(); + } + let (shift, space) = ui.input(|i| (i.modifiers.shift, i.key_down(egui::Key::Space))); + let delta = response.drag_delta(); + if delta != egui::Vec2::ZERO { + if response.dragged_by(egui::PointerButton::Middle) || (space && response.dragged_by(egui::PointerButton::Primary)) { + set.pan[0] += f64::from(delta.x); + set.pan[1] += f64::from(delta.y); + } else if response.dragged_by(egui::PointerButton::Primary) { + let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y)); + if shift { + if dx.abs() >= dy.abs() { + dy = 0.0; + } else { + dx = 0.0; + } + } + set.rotate_y = wrapped(set.rotate_y + dx * DRAG_TURN); + set.rotate_x = wrapped(set.rotate_x + dy * DRAG_TURN); + } + } + if response.hovered() { + let scroll = f64::from(ui.input(|i| i.smooth_scroll_delta.y + (i.zoom_delta() - 1.0) * 200.0)); + if scroll != 0.0 { + set.zoom = (set.zoom * (scroll * 0.002).exp()).clamp(0.1, 8.0); + } + } + if response.has_focus() { + // The view keeps the arrow keys, so they turn it rather than move the focus on. + ui.memory_mut(|m| { + m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + let presses = |key| ui.input_mut(|i| i.count_and_consume_key(egui::Modifiers::NONE, key)) as f64 * KEY_TURN; + let (left, right, up, down) = + (presses(egui::Key::ArrowLeft), presses(egui::Key::ArrowRight), presses(egui::Key::ArrowUp), presses(egui::Key::ArrowDown)); + if left + right + up + down > 0.0 { + set.rotate_y = wrapped(set.rotate_y + right - left); + set.rotate_x = wrapped(set.rotate_x + down - up); + } + } + if response.double_clicked() + && let Some(pos) = response.interact_pointer_pos() + && let Some((blank, key)) = blank + { + // The image on screen is the last one drawn; its panel numbers are used only while it shows + // the same blank of the same document revision. + let picked = CACHE.with(|c| { + let c = c.borrow(); + let shown = c.drawn.map(|d| (d.fold.0, d.fold.1, d.fold.2)); + if shown != Some((key.0, key.1, key.2)) { + return None; + } + let (img, rect) = c.image.as_ref()?; + let x = (pos.x - rect.left()) / rect.width() * img.width as f32; + let y = (pos.y - rect.top()) / rect.height() * img.height as f32; + img.panel_at(x.max(0.0) as u32, y.max(0.0) as u32) + }); + if let Some(p) = picked.and_then(|i| blank.panels.get(i)).and_then(|p| p.point_inside()) { + set.base = Some([p.x, p.y]); + } + } +} + +/// The status line under the view, in English (shown translated). +fn status(blanks: usize, folded: Option<(&Blank, &Folded)>, errors: bool) -> Vec { + let Some((blank, f)) = folded else { + return vec!["Check the fold lines first.".into()]; + }; + let mut out = vec![crate::i18n::fmt( + "Panels: {panels}, hinges: {hinges}", + &[("panels", &blank.panels.len().to_string()), ("hinges", &blank.hinges.len().to_string())], + )]; + if errors { + out.push("Check the fold lines first.".into()); + } + if blanks > 1 { + out.push(crate::i18n::fmt("Other blanks not shown: {count}", &[("count", &(blanks - 1).to_string())])); + } + if let Some(gap) = f.hinges.iter().filter(|h| !h.closes).map(|h| h.gap).reduce(f64::max) { + out.push(crate::i18n::fmt("A joint does not close by {gap} pt.", &[("gap", &format!("{gap:.1}"))])); + } + if !f.collisions.is_empty() { + out.push("Two panels pass through each other.".into()); + } + out +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + crate::panels::empty_state(ui, "box", tl!("No document"), tl!("Open a document to preview its folded shape.")); + return; + }; + let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone()); + let mut set = app.ui.fold_preview.clone().clamped(); + toolbar(app, ui, &mut set); + let (blanks, errors) = CACHE.with(|c| c.borrow_mut().blanks(uid, revision, &doc)); + let base_point = set.base.map(|[x, y]| Point::new(x, y)); + let picked = pick(&blanks, base_point).or_else(|| pick(&blanks, None)); + let folded = picked.and_then(|(b, panel)| { + let blank = blanks.get(b)?; + let key = (uid, revision, b, panel, set.amount.to_bits()); + let (f, ms) = CACHE.with(|c| c.borrow_mut().fold(key, blank, panel, set.amount))?; + Some((blank, f, key, ms)) + }); + + let bottom = ui.spacing().interact_size.y * 3.0 + 12.0; + let size = vec2(ui.available_width().max(64.0), (ui.available_height() - bottom).max(64.0)); + let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag()); + let view_name = set.view().map_or("", |v| v.0); + response.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Fold Preview")); + info.current_text_value = Some(crate::i18n::t(view_name).to_string()); + info + }); + interact(ui, &response, &mut set, folded.as_ref().map(|(b, _, key, _)| (*b, *key))); + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().rect_filled(rect, 2.0, t.pasteboard); + if let Some((blank, f, key, fold_ms)) = &folded { + draw(ui, rect, &doc, *key, blank, f, &set, *fold_ms); + } + if response.has_focus() { + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } + for line in status(blanks.len(), folded.as_ref().map(|(b, f, ..)| (*b, &**f)), errors) { + dim_label(ui, &crate::i18n::msg(&line)); + } + sliders(ui, &mut set); + if set != app.ui.fold_preview { + app.ui.fold_preview = set; + } +} + +/// Draws `blank` folded as `f` (the fold `key` names) into `rect`, with the print of `doc`. The image +/// is rendered again only when the fold, the view, the inside color or the print changed. +#[allow(clippy::too_many_arguments)] +fn draw(ui: &Ui, rect: Rect, doc: &Arc, key: FoldKey, blank: &Blank, f: &Folded, set: &Settings, fold_ms: f64) { + // Pixels per point of the view, lowered when the window has more pixels than the view may have + // in all or along either side, so the image keeps the window's proportions. + let (w, h) = (f64::from(rect.width()), f64::from(rect.height())); + let mut ppp = f64::from(ui.ctx().pixels_per_point()); + let area = w * h * ppp * ppp; + if area > f64::from(MAX_PIXELS) { + ppp *= (f64::from(MAX_PIXELS) / area).sqrt(); + } + ppp = ppp.min(f64::from(MAX_SIDE) / w.max(h).max(1.0)); + let width = ((w * ppp).floor() as u32).clamp(1, MAX_SIDE); + let height = ((h * ppp).floor() as u32).clamp(1, MAX_SIDE); + let Some((lo, hi)) = raster::bounds(blank, f) else { return }; + let center = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0]; + let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() / 2.0; + let mut fit = FIT * f64::from(width.min(height)) / radius.max(1e-6); + if set.perspective > 0.0 { + // The eye at two radii from the middle or farther, so at a zoom of 1 the whole blank is in + // front of it. + let focal = f64::from(width.min(height)) / 2.0 / (set.perspective.to_radians() / 2.0).tan(); + fit = fit.min(focal / (2.0 * radius.max(1e-6))); + } + let camera = Camera { + width, + height, + rotate_x: set.rotate_x, + rotate_y: set.rotate_y, + scale: fit * set.zoom, + pan: [set.pan[0] * ppp, set.pan[1] * ppp], + perspective: set.perspective, + center, + }; + let inside = inside_color(doc, &set.inside).unwrap_or([255; 4]); + // While the print of a new revision renders, the last one of the same blank and setting is + // drawn; a print of another document, blank or Show Fold Lines setting is not. + let print = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let region = print_region(blank)?; + let (pw, ph, scale) = print_size(region); + let pkey = PrintKey { + uid: key.0, + revision: key.1, + fold_lines: set.show_fold_lines, + region: [region.x0.to_bits(), region.y0.to_bits(), region.x1.to_bits(), region.y1.to_bits()], + width: pw, + height: ph, + }; + c.update_print(ui.ctx(), doc, pkey, region, scale); + c.print_for(&pkey) + }); + let draw_key = DrawKey { fold: key, camera, inside, print: print.as_ref().map(|(k, _)| *k) }; + let kept = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let Some(tex) = c.tex.as_ref().filter(|_| c.drawn == Some(draw_key)).map(|t| t.id()) else { return false }; + ui.painter().image(tex, rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + if let Some((_, at)) = &mut c.image { + *at = rect; + } + true + }); + if kept { + return; + } + let t0 = crate::now_ms(); + let scene = raster::Scene { blank, folded: f, print: print.as_ref().map(|(_, p)| &**p), inside, outside: [255; 4], camera }; + let Some(img) = raster::render(&scene) else { return }; + let draw_ms = crate::now_ms() - t0; + let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + c.drawn = Some(draw_key); + c.renders += 1; + match &mut c.tex { + Some(tex) => tex.set(color, egui::TextureOptions::LINEAR), + None => c.tex = Some(ui.ctx().load_texture("fold-preview", color, egui::TextureOptions::LINEAR)), + } + if let Some(tex) = &c.tex { + let uv = Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + ui.painter().image(tex.id(), rect, uv, Color32::WHITE); + } + c.frame = Some(Frame { width: img.width, height: img.height, fold_ms, draw_ms }); + c.image = Some((img, rect)); + }); +} + +#[cfg(test)] +pub(crate) fn prints_rendered() -> u64 { + CACHE.with(|c| c.borrow().prints) +} + +#[cfg(test)] +pub(crate) fn last_image() -> Option { + CACHE.with(|c| c.borrow().image.as_ref().map(|(i, _)| i.clone())) +} + +/// The folds worked out and the images rendered so far. +#[cfg(test)] +pub(crate) fn work_done() -> (u64, u64) { + CACHE.with(|c| (c.borrow().folds, c.borrow().renders)) +} + +/// The screen rect the last image filled. +#[cfg(test)] +pub(crate) fn last_rect() -> Option { + CACHE.with(|c| c.borrow().image.as_ref().map(|(_, r)| *r)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs new file mode 100644 index 0000000000..c3c69c3f31 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -0,0 +1,505 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use std::sync::Arc; + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; + +use super::{Cache, ID, PrintKey, Settings, inside_color, last_image, last_rect, prints_rendered, show, status, work_done}; +use crate::{VectorcraftApp, menus}; + +/// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each +/// side) and a red square printed on the base, nothing selected → (app, the red square's id). +fn app() -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = [ + path(&mut app, "M140 140 L240 140"), + path(&mut app, "M240 140 L240 240"), + path(&mut app, "M240 240 L140 240"), + path(&mut app, "M140 240 L140 140"), + ]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + let red = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("paint.setFill", json!({ "color": "#ff0000" })).unwrap(); + app.run("paint.setStroke", json!({ "none": true })).unwrap(); + app.run("object.arrange.sendToBack", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, red) +} + +/// Draws the window in a 520 × 440 frame, twice (egui lays out on the first). +fn frame(app: &mut VectorcraftApp) { + frame_at(app, 1.0); +} + +/// [`frame`] at `zoom` pixels per point. +fn frame_at(app: &mut VectorcraftApp, zoom: f32) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(zoom); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(520.0, 440.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } +} + +fn color_at(img: &vectorcraft_three_d::fold::raster::Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// The color at the middle of the window's last image. +fn middle(img: &vectorcraft_three_d::fold::raster::Image) -> [u8; 4] { + color_at(img, img.width / 2, img.height / 2) +} + +#[test] +fn the_menu_item_and_the_panel_button_show_the_window_and_a_second_run_keeps_it() { + let (mut app, _) = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Fold Preview").expect("listed"); + assert_eq!((item.command.as_deref(), &item.params), (Some("ui.foldPreview"), &json!({}))); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "the window opens"); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "a second run leaves it open"); + let text = crate::tests_labels::painted_text(&mut app, super::super::show); + assert!(text.contains("Fold Preview"), "the Fold Lines panel has the button: {text}"); +} + +#[test] +fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { + let (mut app, _) = app(); + let r = app + .run( + "ui.foldPreview", + json!({"amount": 0.5, "view": "top", "zoom": 2, "perspective": 40, "inside": "#00ff00", "showFoldLines": true, "base": [120, 190]}), + ) + .unwrap(); + let want = Settings { + amount: 0.5, + rotate_x: 90.0, + rotate_y: 0.0, + zoom: 2.0, + pan: [0.0; 2], + perspective: 40.0, + inside: "#00ff00".into(), + show_fold_lines: true, + base: Some([120.0, 190.0]), + }; + assert_eq!(app.ui.fold_preview, want); + assert_eq!(r["rotateX"], 90.0, "{r}"); + assert!(r.get("frame").is_some(), "{r}"); + app.run("ui.foldPreview", json!({"rotateX": -30, "rotateY": 170, "base": null})).unwrap(); + assert_eq!((app.ui.fold_preview.rotate_x, app.ui.fold_preview.rotate_y, app.ui.fold_preview.base), (-30.0, 170.0, None)); + let kept = app.ui.fold_preview.clone(); + for (p, want) in [ + (json!({"amount": 2}), "`amount` must be a number from 0 to 1"), + (json!({"amount": "half"}), "`amount` must be a number from 0 to 1"), + (json!({"view": "sideways"}), "`view` must be one of"), + (json!({"rotateX": 200}), "`rotateX` must be a number from -180 to 180"), + (json!({"zoom": 0}), "`zoom` must be a number from 0.1 to 8"), + (json!({"perspective": 170}), "`perspective` must be a number from 0 to 160"), + (json!({"inside": "no such swatch"}), "`inside` must be #rrggbb"), + (json!({"inside": 7}), "`inside` must be #rrggbb"), + (json!({"showFoldLines": "yes"}), "`showFoldLines` must be true or false"), + (json!({"base": [1, "2"]}), "`base` must be a point"), + (json!({"base": [5, 5]}), "`base` is in no panel"), + (json!({"amount": 0.2, "zoom": 99}), "`zoom` must be a number"), + ] { + let e = app.run("ui.foldPreview", p.clone()).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + assert_eq!(app.ui.fold_preview, kept, "{p} sets nothing"); + } + // A swatch with a plain color names the inside. + app.run("ui.foldPreview", json!({"inside": "White"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "White"); + // So does one whose name starts with #, and a swatch's name comes before a #rrggbb that reads the same. + app.run("swatch.new", json!({"name": "#brand", "color": "#0000ff"})).unwrap(); + app.run("swatch.new", json!({"name": "#00ff00", "color": "#0000ff"})).unwrap(); + app.run("ui.foldPreview", json!({"inside": "#brand"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "#brand"); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255])); + // White, the default, stays white beside a swatch named #ffffff. + app.run("swatch.new", json!({"name": "#ffffff", "color": "#0000ff"})).unwrap(); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, &Settings::default().inside), Some([255; 4])); + assert_eq!(inside_color(doc, "#ffffff"), Some([0, 0, 255, 255])); + app.run("ui.foldPreview", json!({"inside": ""})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, ""); +} + +#[test] +fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs() { + let (mut app, _) = app(); + // Flat, from the front: the base's print, red, fills the middle. + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let before = prints_rendered(); + frame(&mut app); + assert!(prints_rendered() > before, "the print is rendered on this thread without a worker"); + let img = last_image().expect("a frame"); + let [r, g, b, a] = middle(&img); + assert!(r > 150 && g < 40 && b < 40 && a == 255, "red print: {:?}", [r, g, b, a]); + let state = app.run("ui.foldPreview", json!({})).unwrap(); + assert_eq!((state["frame"]["width"].as_u64(), state["frame"]["height"].as_u64()), (Some(u64::from(img.width)), Some(u64::from(img.height)))); + // From the back, the base's inside shows in the inside color. + app.run("ui.foldPreview", json!({"view": "back", "inside": "#00ff00"})).unwrap(); + frame(&mut app); + let [r, g, b, _] = middle(&last_image().expect("a frame")); + assert!(r < 40 && g > 150 && b < 40, "green inside: {:?}", [r, g, b]); + // Folded and seen from the front, the walls stand edge on: the base fills the same place. + app.run("ui.foldPreview", json!({"amount": 1, "view": "front"})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let [r, ..] = middle(&img); + assert!(r > 150, "the base still shows its print: {:?}", middle(&img)); + // The same print is not rendered again while the document does not change. + let prints = prints_rendered(); + frame(&mut app); + assert_eq!(prints_rendered(), prints); +} + +#[test] +fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() { + let (mut app, _) = app(); + // Without perspective, the base and the two walls behind it that face the viewer show. + let mut flat = None; + for perspective in [0, 60, 160] { + app.run("ui.foldPreview", json!({"amount": 1, "view": "threeQuarter", "zoom": 1, "perspective": perspective})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let mut shown: Vec = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter_map(|(x, y)| img.panel_at(x, y)).collect(); + shown.sort_unstable(); + shown.dedup(); + let flat = flat.get_or_insert_with(|| shown.clone()); + assert_eq!(flat.len(), 3); + assert_eq!(&shown, flat, "{perspective}°: the same panels show"); + let edge = (0..img.width).flat_map(|x| [(x, 0), (x, img.height - 1)]).chain((0..img.height).flat_map(|y| [(0, y), (img.width - 1, y)])); + assert!(edge.into_iter().all(|(x, y)| img.panel_at(x, y).is_none()), "{perspective}°: nothing reaches the edge of the view"); + } +} + +#[test] +fn a_window_with_more_pixels_than_the_view_may_have_is_drawn_smaller() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + frame_at(&mut app, 8.0); + let img = last_image().expect("a frame"); + assert!(u64::from(img.width) * u64::from(img.height) <= u64::from(vectorcraft_three_d::fold::raster::MAX_PIXELS), "{}×{}", img.width, img.height); + assert!(img.width > 1000, "still sharper than one pixel a point: {}", img.width); + let [r, ..] = middle(&img); + assert!(r > 150, "the base's print shows: {:?}", middle(&img)); +} + +#[test] +fn the_print_leaves_out_the_fold_lines_unless_they_are_shown() { + let (mut app, red) = app(); + // Without the red square, the base's middle shows the board with no art; with a crease drawn + // across the middle and the fold lines shown, the crease's color shows there. + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let mid = app.run("path.create", json!({ "d": "M140 190 L240 190" })).unwrap()["id"].as_u64().unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": [mid] })).unwrap(); + app.run("select.set", json!({ "ids": [mid] })).unwrap(); + app.run("stroke.set", json!({ "weight": 20 })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front", "zoom": 1})).unwrap(); + frame(&mut app); + let plain = middle(&last_image().expect("a frame")); + app.run("ui.foldPreview", json!({"showFoldLines": true})).unwrap(); + frame(&mut app); + let lined = middle(&last_image().expect("a frame")); + assert_ne!(plain, lined, "the crease shows only with Show Fold Lines on"); + assert!(plain[0] > 200 && plain[1] > 200 && plain[2] > 200, "the board is white where the print has no art: {plain:?}"); +} + +#[test] +fn the_window_says_when_there_is_nothing_to_fold() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Check the fold lines first."), "{text}"); + let mut none = VectorcraftApp::new(Session::new(), Default::default()); + let text = crate::tests_labels::painted_text(&mut none, show); + assert!(text.contains("Open a document to preview its folded shape."), "{text}"); +} + +#[test] +fn the_settings_are_kept_with_the_ui_state() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0.25, "view": "left"})).unwrap(); + let saved: Value = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["fold_preview"]["amount"], 0.25, "{}", saved["fold_preview"]); + let back: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(back.fold_preview, app.ui.fold_preview); +} + +#[test] +fn saved_settings_out_of_range_are_brought_into_range() { + let (mut app, _) = app(); + app.ui.fold_preview = Settings { + amount: 3.0, + rotate_x: 200.0, + rotate_y: 180.0, + zoom: 0.0, + pan: [f64::NAN, 4.0], + perspective: -5.0, + base: Some([f64::INFINITY, 0.0]), + ..Settings::default() + }; + frame(&mut app); + let set = &app.ui.fold_preview; + assert_eq!( + (set.amount, set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective, set.base), + (1.0, -160.0, 180.0, 0.1, [0.0, 4.0], 0.0, None) + ); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Check the fold lines first."), "the blank folds: {text}"); + assert!(last_image().is_some(), "and is drawn"); +} + +/// A window kept open over frames, as the app draws it. +struct View { + ctx: egui::Context, + time: f64, +} + +impl View { + fn new(app: &mut VectorcraftApp) -> Self { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = View { ctx, time: 0.0 }; + v.idle(app); + v + } + + fn step(&mut self, app: &mut VectorcraftApp, events: Vec, modifiers: Modifiers) { + self.time += 0.05; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(520.0, 440.0)); + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } + + fn idle(&mut self, app: &mut VectorcraftApp) { + for _ in 0..3 { + self.step(app, vec![], Modifiers::NONE); + } + } + + /// Presses `button` at `at`, drags by `by` in four steps and lets go, holding `modifiers`. + fn drag(&mut self, app: &mut VectorcraftApp, at: Pos2, by: egui::Vec2, button: PointerButton, modifiers: Modifiers) { + let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers }; + self.step(app, vec![Event::PointerMoved(at)], modifiers); + self.step(app, vec![press(at, true)], modifiers); + for k in 1..=4 { + self.step(app, vec![Event::PointerMoved(at + by * (k as f32 / 4.0))], modifiers); + } + self.step(app, vec![press(at + by, false)], modifiers); + self.idle(app); + } + + fn click(&mut self, app: &mut VectorcraftApp, at: Pos2) { + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + self.step(app, vec![Event::PointerMoved(at)], Modifiers::NONE); + self.step(app, vec![press(true)], Modifiers::NONE); + self.step(app, vec![press(false)], Modifiers::NONE); + } + + fn key(&mut self, app: &mut VectorcraftApp, key: egui::Key) { + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + self.step(app, vec![press], Modifiers::NONE); + self.step(app, vec![], Modifiers::NONE); + } +} + +/// The app showing the tray flat from the front, in a [`View`], and the middle of the view. +fn front_view() -> (VectorcraftApp, View, Pos2) { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let view = View::new(&mut app); + let at = last_rect().expect("the view is drawn").center(); + (app, view, at) +} + +#[test] +fn a_drag_turns_the_view_and_a_shift_drag_keeps_to_one_axis() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_y <= 20.0 + 1e-9, "{set:?}"); + assert!(set.rotate_x > 2.0 && set.rotate_x <= 10.0 + 1e-9, "{set:?}"); + app.run("ui.foldPreview", json!({"view": "front"})).unwrap(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::SHIFT); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_x == 0.0, "only the larger move turns the view: {set:?}"); +} + +#[test] +fn a_middle_drag_moves_the_view_and_the_wheel_zooms_it() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(30.0, -10.0), PointerButton::Middle, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.pan[0] > 0.0 && set.pan[1] < 0.0, "{set:?}"); + assert_eq!((set.rotate_x, set.rotate_y), (0.0, 0.0), "the view does not turn"); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 60.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }; + view.step(&mut app, vec![Event::PointerMoved(at), wheel], Modifiers::NONE); + for _ in 0..20 { + view.step(&mut app, vec![], Modifiers::NONE); + } + assert!(app.ui.fold_preview.zoom > 1.05, "{:?}", app.ui.fold_preview); +} + +#[test] +fn the_arrow_keys_turn_the_focused_view_and_keep_the_focus() { + let (mut app, mut view, at) = front_view(); + view.click(&mut app, at); + view.idle(&mut app); + // Up first: the toolbar is above the view, where the focus would go if the view let it. + view.key(&mut app, egui::Key::ArrowUp); + view.key(&mut app, egui::Key::ArrowRight); + view.key(&mut app, egui::Key::ArrowRight); + let set = &app.ui.fold_preview; + assert_eq!((set.rotate_x, set.rotate_y), (-5.0, 10.0), "every press turns the view by 5°"); + // A focused view seen from the back stays there until a key turns it. + app.run("ui.foldPreview", json!({"view": "back"})).unwrap(); + view.idle(&mut app); + assert_eq!(app.ui.fold_preview.rotate_y, 180.0); +} + +#[test] +fn a_double_click_on_a_panel_makes_it_the_base() { + let (mut app, mut view, at) = front_view(); + // The left wall is the base; the middle of the view shows the tray's base panel. + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + view.click(&mut app, at); + let [x, y] = app.ui.fold_preview.base.expect("a base"); + assert!((140.0..240.0).contains(&x) && (140.0..240.0).contains(&y), "the base panel is picked: {x}, {y}"); +} + +#[test] +fn a_double_click_as_the_document_changes_picks_nothing_from_the_old_image() { + let (mut app, mut view, at) = front_view(); + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + view.step(&mut app, vec![press(true)], Modifiers::NONE); + // The document changes between the image on screen and the release that ends the double-click. + app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap(); + view.step(&mut app, vec![press(false)], Modifiers::NONE); + assert_eq!(app.ui.fold_preview.base, Some([120.0, 190.0]), "the base is kept"); +} + +#[test] +fn the_view_is_folded_and_drawn_again_only_when_something_changes() { + let (mut app, mut view, _) = front_view(); + let (folds, renders) = work_done(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders), "nothing changed: no fold and no render"); + app.run("ui.foldPreview", json!({"rotateY": 10})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders + 1), "a turn renders once and does not fold again"); + app.run("ui.foldPreview", json!({"amount": 0.5})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds + 1, renders + 2), "a new amount folds and renders once"); +} + +#[test] +fn a_short_wide_window_keeps_its_proportions() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(2200.0, 260.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + } + let (img, rect) = (last_image().expect("a frame"), last_rect().expect("a rect")); + let (image, window) = (f64::from(img.width) / f64::from(img.height), f64::from(rect.width() / rect.height())); + assert!(img.width <= vectorcraft_three_d::fold::raster::MAX_SIDE, "{}", img.width); + assert!((image - window).abs() / window < 0.02, "image {image}, window {window}"); +} + +#[test] +fn a_print_of_another_blank_or_setting_is_not_drawn_while_the_new_one_renders() { + let key = PrintKey { uid: 1, revision: 5, fold_lines: false, region: [0, 0, 10, 10], width: 1, height: 1 }; + let region = vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0); + let print = vectorcraft_three_d::fold::raster::Print::new(region, 1, 1, vec![255; 4]).expect("a print"); + let cache = Cache { print: Some((key, Arc::new(print))), ..Default::default() }; + assert!(cache.print_for(&PrintKey { revision: 6, ..key }).is_some(), "a newer revision of the same blank keeps the last print"); + for other in [PrintKey { uid: 2, ..key }, PrintKey { fold_lines: true, ..key }, PrintKey { region: [0, 0, 20, 10], ..key }] { + assert!(cache.print_for(&other).is_none(), "{other:?}"); + } +} + +#[test] +fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { + use vectorcraft_three_d::fold::{Blank, Folded, FoldedHinge}; + let hinge = |tree, closes, gap| FoldedHinge { a: 0, b: 1, angle: 90.0, tree, closes, gap }; + let f = Folded { + base: 0, + panels: vec![], + order: vec![], + hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], + collisions: vec![(0, 1)], + }; + let lines = status(3, Some((&Blank::default(), &f)), true); + assert_eq!( + lines, + [ + "Panels: 0, hinges: 0", + "Check the fold lines first.", + "Other blanks not shown: 2", + "A joint does not close by 12.3 pt.", + "Two panels pass through each other." + ] + ); + let f = Folded { hinges: vec![hinge(false, true, 0.05)], collisions: vec![], ..f }; + assert_eq!(status(1, Some((&Blank::default(), &f)), false), ["Panels: 0, hinges: 0"]); +} + +#[test] +fn the_window_says_when_folded_panels_pass_through_each_other() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. Folded + // about the base, the lid crosses the taller wall. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M0 0 L310 0 L310 50 L0 50 Z"); + let creases = [path(&mut app, "M120 0 L120 50"), path(&mut app, "M150 0 L150 50"), path(&mut app, "M250 0 L250 50")]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"base": [200, 25], "amount": 1})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Two panels pass through each other."), "{text}"); + assert!(!text.contains("A joint does not close"), "{text}"); +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 011af4b171..8a1666b260 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,11 +1,12 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and //! `tool.setOption`. +pub mod bridge; pub mod corner; pub mod dashes; pub mod set_corners; @@ -74,6 +75,7 @@ pub fn menu() -> Vec { Item::Cmd("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null), Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), + Item::Cmd("Smooth Bridge…", bridge::COMMAND, Value::Null), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), Item::Cmd("Tangent Circle…", tangent_circle::COMMAND, Value::Null), Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), @@ -246,12 +248,15 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options. When the tool refuses one of them, nothing is set and the dialog +/// stays open. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let tool = d.str("__tool"); let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let r = app.run("tool.setOption", json!({ "tool": tool, "values": values })); - app.ui.dialog = None; + if r.is_ok() { + app.ui.dialog = None; + } r } diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..5d6a18d282 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -0,0 +1,155 @@ +//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller +//! 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}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::widgets; + +/// The command, and its dialog's kind. +pub const COMMAND: &str = "addon.pathtools.bridge"; +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, "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 radius, or with Constant Gap the gap. +fn params(d: &Dialog) -> Value { + 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 { + 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)); + false +} + +/// OK: run the command (keep its preview) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { + app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() + } + + #[test] + fn smooth_bridge_opens_its_dialog_previews_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (circle(&mut app, 100.0, 20.0), circle(&mut app, 160.0, 20.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Smooth Bridge…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + 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", "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())); + assert_eq!(count(&app), 1, "previewed: one outline in place of the circles"); + crate::dialogs::cancel(&mut app); + assert_eq!(count(&app), 2, "rolled back"); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + let n = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("keepOriginals".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + 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/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 3f7006e536..e714b85aa2 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -329,3 +329,45 @@ fn common_tangents_previews_cancels_and_runs_on_ok() { assert_eq!((steps(&app), count(&app)), (n, nodes)); assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); } + +/// Common Tangents… on a point and an ellipse: every Tangents choice previews the same two lines +/// from the point, OK keeps them as one step, and a point inside the ellipse changes nothing and +/// says why. +#[test] +fn common_tangents_on_a_point_gives_the_same_lines_for_every_choice() { + let mut app = app(); + let oval = app.run("shape.ellipse", json!({"x": 180.0, "y": 120.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap(); + let point = + |app: &mut VectorcraftApp, x: f64, y: f64| app.run("path.create", json!({"anchors": [{"x": x, "y": y}]})).unwrap()["id"].as_u64().unwrap(); + let dot = point(&mut app, 40.0, 150.0); + app.run("select.set", json!({"ids": [oval, dot]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count(); + let (n, nodes) = (steps(&app), count(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Common Tangents…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + for (_, kind) in super::TANGENT_KINDS { + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "tangents".into(), json!(kind)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 2, "{kind}: the two lines from the point"); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 2), "one undo step"); + + // A point inside the ellipse: nothing changes, and a message says why. + let inside = point(&mut app, 220.0, 150.0); + app.run("select.set", json!({"ids": [oval, inside]})).unwrap(); + let (n, nodes) = (steps(&app), count(&app)); + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n, nodes)); + assert!(app.ui.status.contains("The point lies inside the path"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7ae09974e6..11c87d07ac 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -82,6 +82,7 @@ impl VectorcraftApp { slices: None, print_tiling: None, live_paint_gaps: None, + find_font: None, hidden_chars: Default::default(), spelling: Default::default(), selection_marks: Default::default(), @@ -89,7 +90,9 @@ impl VectorcraftApp { selection_box: None, selection_bounds: None, content_bounds: None, + three_d_exportable: None, pixel_aligned: None, + symbol_instances: None, plugin_keys: Default::default(), placed_keys: Default::default(), cursors: Default::default(), @@ -161,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(), @@ -194,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(), @@ -583,6 +588,7 @@ impl VectorcraftApp { self.ime_caret_rect = None; scrub::begin_frame(self, &ctx); font_menu::end_stale_preview(self, &ctx); + font_menu::apply_preview_size(self, &ctx); tools_float::track(self, &ctx); // A selection move released over a panel ends before any panel sees the release (#2826). canvas::release_over_panel(self, &ctx); @@ -631,7 +637,10 @@ impl VectorcraftApp { plugin_runs::show(self, &ctx); trace_runs::show(self, &ctx); opening::show(self, &ctx); + // 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/caches.rs b/crates/ui-egui/src/caches.rs index 6dc036fcf2..be5ff73c54 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -42,6 +42,10 @@ pub struct CanvasCache { pub print_tiling: Option, /// The gap lines View → Show Live Paint Gaps draws for (document uid, revision). pub live_paint_gaps: Option, + /// Type → Find Font's list of the document's fonts and whether the document misses one, for a + /// version of the document's content and of the available fonts: the dialog reads them every + /// frame. + pub find_font: Option, /// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame /// that does not draw them drops them ([`canvas::show`]). pub hidden_chars: canvas::HiddenChars, @@ -61,9 +65,15 @@ pub struct CanvasCache { pub selection_bounds: Option<((u64, u64), Option)>, /// [`VectorcraftApp::content_bounds`] for (document uid, revision). pub content_bounds: Option<((u64, u64), Option)>, + /// Whether the 3D and Materials panel's Export 3D Object button is available (a selected + /// object has a 3D effect that `assets.add3D` exports) for (document uid, revision). + pub three_d_exportable: Option<((u64, u64), bool)>, /// The Transform panel's Align to Pixel Grid state (on, off or mixed, and whether every /// selected object can be aligned) for (document uid, revision). pub pixel_aligned: Option<((u64, u64), Option)>, + /// The symbol instances in the selection and its groups, for (document uid, revision): the + /// Properties and Symbols panels read them every frame. + pub symbol_instances: Option<((u64, u64), SymbolInstances)>, /// [`CacheKey::plugins`] by document uid, with the plug-in revision /// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at. pub plugin_keys: std::collections::HashMap, @@ -111,10 +121,48 @@ pub type SliceCache = ((u64, u64), std::sync::Arc>); +/// [`CanvasCache::find_font`]: the document's fonts as `text.fonts` lists them, and whether +/// [`vectorcraft_engine::cmd::fontfiles::missing_fonts`] finds any (`None` until it is asked). +#[derive(Clone, Debug)] +pub struct FindFontCache { + /// The document and the content and fonts the answers were worked out from. + pub key: FontsKey, + pub fonts: std::sync::Arc>, + pub missing: Option, +} + +/// A document's uid, a version of its content (compared by identity) and the font database's +/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's +/// allocation, so a later version is never placed at the same address while the key is kept. +#[derive(Clone, Debug)] +pub struct FontsKey { + pub uid: u64, + pub doc: std::sync::Weak, + pub generation: u64, +} + +impl PartialEq for FontsKey { + fn eq(&self, other: &Self) -> bool { + self.uid == other.uid && self.generation == other.generation && std::sync::Weak::ptr_eq(&self.doc, &other.doc) + } +} + /// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they /// agree and `None` when they differ, with whether every one can be aligned. pub type PixelAligned = (Option, bool); +/// [`CanvasCache::symbol_instances`]: the symbol instances in the selection and its groups. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SymbolInstances { + /// Each instance's id, in the order the selection's subtrees list them. + pub ids: Vec, + /// One of them has appearance changes of its own (`symbol_overrides`). + pub changed: bool, + /// One of them has a scale, rotation or shear that Reset Transformation would change; measured + /// on the first read. + pub transformed: Option, +} + /// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision). pub type PrintTilingCache = ((u64, u64), std::sync::Arc>); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4b9632fd47..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,15 +63,17 @@ 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}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; pub use selection_marks::SelectionMarks; -#[cfg(test)] -pub(crate) use task_bar::chip_paints; use task_bar::task_bar; +#[cfg(test)] +pub(crate) use task_bar::{chip_paints, images_with_other_art}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; @@ -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/context.rs b/crates/ui-egui/src/canvas/context.rs index d8cd85d13a..9cdec919b5 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -75,10 +75,11 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } - // A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. - if let widgets::PanelDrag::Symbol(name) = &*d { + // A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. A + // symbol of another document is added to this one first. + if let widgets::PanelDrag::Symbol { document, name } = &*d { let at = xf.to_doc(pos); - if let Err(e) = app.run("symbol.place", json!({"name": name, "x": at.x, "y": at.y})) { + if let Err(e) = app.run("symbol.placeFromDocument", json!({"sourceDocument": document, "name": name, "x": at.x, "y": at.y})) { app.status(e); } return; @@ -155,7 +156,7 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons // Art dragged back onto the canvas: its move was already dropped. (A symbol was placed // above.) widgets::PanelDrag::Art(_) - | widgets::PanelDrag::Symbol(_) + | widgets::PanelDrag::Symbol { .. } | widgets::PanelDrag::LibrarySymbol { .. } | widgets::PanelDrag::LibraryGraphic { .. } => return, // A Libraries panel style or group only moves within that panel. diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index f605e5e947..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)>, @@ -317,7 +319,7 @@ pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response, // The art the drag started with: the release rolls the move back to it, and an Alt-copy's // copies, selected while it previews, go with that. let ids = it.selection.objects.clone(); - egui::DragAndDrop::set_payload(ui.ctx(), widgets::PanelDrag::Art(ids)); + widgets::drag_art(ui.ctx(), st.uid, ids); true } 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/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index e49fa9bfc7..c133c003f8 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -92,6 +92,31 @@ fn smooth_tool_on_paths(app: &VectorcraftApp, ctx: &egui::Context) -> bool { found } +/// Whether the selection holds images together with other objects, for which the bar offers Make +/// Clipping Mask: at least one selected object is an image and at least one is not (a selected id +/// with no object counts as not an image). The walk stops once it has seen both. The answer is kept +/// in `ctx` for the document's revision, as [`smooth_tool_on_paths`] keeps its own. +pub(crate) fn images_with_other_art(st: &vectorcraft_engine::DocState, ctx: &egui::Context) -> bool { + let id = task_bar_id().with("mixed"); + let key = (st.uid, st.revision); + if let Some((k, found)) = ctx.data(|d| d.get_temp::<((u64, u64), bool)>(id)) + && k == key + { + return found; + } + let (mut image, mut other) = (false, false); + let found = st.selection.objects.iter().any(|id| { + if st.doc.node(*id).is_some_and(|o| matches!(o.kind, NodeKind::Image(_))) { + image = true; + } else { + other = true; + } + image && other + }); + ctx.data_mut(|d| d.insert_temp(id, (key, found))); + found +} + /// Whether the bar shows its blank canvas actions, Draw (Pencil) and Place Image: a selection tool is /// in use and the active document has no artwork, only layers and guides. fn blank_canvas(app: &VectorcraftApp) -> bool { @@ -192,10 +217,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { _ => None, }); // Images and vector art selected together: a clipping mask is the likely next step. - let mixed = n > 1 && { - let images = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).filter(|o| matches!(o.kind, NodeKind::Image(_))).count(); - images > 0 && images < n - }; + let mixed = n > 1 && images_with_other_art(st, ui.ctx()); // An Image Trace object: the group the engine names "Image Trace", its source image first. let is_trace = is_group && first.as_ref().is_some_and(|f| { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3f8cc4a661..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()); @@ -9028,6 +9218,36 @@ fn escape_while_editing_in_isolation_returns_to_selection_tool_and_keeps_isolati assert!(app.session.active().unwrap().isolation.is_none(), "2nd Escape must exit isolation mode"); } +/// One Escape leaves isolation mode from a sublayer two levels down, where Exit Isolation Mode goes +/// up one layer at a time. +#[test] +fn escape_leaves_an_isolated_sublayer_in_one_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let top = app.session.active().unwrap().doc.layers[0].id; + let mid = app.session.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap(); + let deep = app.session.execute("layer.newSublayer", &json!({"parent": mid})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("layer.setCurrent", &json!({"id": deep})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + app.session.execute("object.isolate", &json!({"id": deep})).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| { + crate::shortcuts::handle(app, ui.ctx()); + show(app, ui) + }); + out.textures_delta.clear(); + }; + let esc = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + timed(&mut app, 0.0, vec![]); + assert_eq!(app.session.active().unwrap().isolation, Some(vectorcraft_doc::NodeId(deep))); + timed(&mut app, 1.0, vec![esc(true), esc(false)]); + timed(&mut app, 1.1, vec![]); + assert_eq!(app.session.active().unwrap().isolation, None, "one Escape leaves every level"); +} + #[test] fn a_symbol_dropped_on_the_canvas_is_placed_there() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -9040,7 +9260,8 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); // Released over empty canvas: an instance centred there. let at = xf.to_screen(Point::new(250.0, 180.0)); - egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol(name.clone())); + let document = app.session.active().unwrap().uid; + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document, name: name.clone() }); let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); let st = app.session.active().unwrap(); @@ -9051,6 +9272,106 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() { assert!((c - xf.to_doc(at)).hypot() < 1e-6, "{c:?}"); } +/// A new active document with a symbol `name` made from a `w` by `h` rectangle and no art; → its +/// uid. +fn document_with_symbol(app: &mut VectorcraftApp, name: &str, w: f64, h: f64) -> u64 { + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": w, "height": h})).unwrap(); + app.session.execute("symbol.new", &json!({"name": name})).unwrap(); + app.session.execute("edit.clear", &json!({})).unwrap(); + app.session.active().unwrap().uid +} + +/// The natural size the active document records for symbol `name`. +fn symbol_size(app: &VectorcraftApp, name: &str) -> (f64, f64) { + let st = app.session.active().unwrap(); + let size = st.doc.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get(name)).cloned().unwrap(); + (size[0].as_f64().unwrap(), size[1].as_f64().unwrap()) +} + +/// A symbol dragged from one document's Symbols panel and released on the canvas after another +/// document with a different symbol of the same name became active places the dragged symbol: it +/// is added under a free name, the other document's symbol is left as it was, the source document +/// is not changed, and one Undo takes back both the symbol and the instance. +#[test] +fn a_symbol_dragged_from_another_document_places_that_documents_symbol() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + let ctx = egui::Context::default(); + // While Leaf is held, a document with a Leaf of its own becomes active. + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + document_with_symbol(&mut app, "Leaf", 10.0, 70.0); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let undo = app.session.active().unwrap().history.undo.len(); + let at = xf.to_screen(Point::new(250.0, 180.0)); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Leaf", "Leaf 2"]); + assert_eq!(st.history.undo.len(), undo + 1, "added and placed as one undo step"); + let placed = st.selection.objects.first().copied().expect("the placed instance is selected"); + let n = st.doc.node(placed).unwrap(); + assert!(matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Leaf 2"), "{:?}", n.kind); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 40.0).abs() < 1e-6 && (b.height() - 20.0).abs() < 1e-6, "the dragged symbol's size: {b:?}"); + assert!((b.center() - xf.to_doc(at)).hypot() < 1e-6, "{b:?}"); + assert_eq!(symbol_size(&app, "Leaf"), (10.0, 70.0), "this document's Leaf is unchanged"); + app.run("edit.undo", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Leaf"]); + assert!(st.doc.node(placed).is_none()); + assert!(app.session.set_active(0)); + assert_eq!(app.session.active().unwrap().uid, source); + assert_eq!(app.session.active().unwrap().doc.symbols.len(), 1, "the source document is unchanged"); + assert_eq!(symbol_size(&app, "Leaf"), (40.0, 20.0)); +} + +/// A symbol dragged from a document that was closed before the release places nothing, even +/// where the active document has a symbol of the same name. +#[test] +fn a_symbol_whose_document_closed_places_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + document_with_symbol(&mut app, "Leaf", 10.0, 70.0); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(app.session.documents().iter().all(|d| d.uid != source)); + let ctx = egui::Context::default(); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let undo = app.session.active().unwrap().history.undo.len(); + let at = xf.to_screen(Point::new(250.0, 180.0)); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), undo, "no edit"); + assert!(st.selection.objects.is_empty(), "nothing placed"); +} + +/// The chip at the pointer shows the dragged symbol from the document it was dragged from after +/// another document, without a symbol of that name, became active. +#[test] +fn the_pointer_chip_of_a_dragged_symbol_shows_its_own_documents_symbol() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))); + let run = |events| { + let mut out = + ctx.run_ui(egui::RawInput { screen_rect, events, ..Default::default() }, |ui| crate::panels::swatches::drag_preview(&app, ui.ctx())); + out.textures_delta.clear(); + out + }; + // The chip's area is drawn from its second frame. + run(vec![egui::Event::PointerMoved(pos2(200.0, 150.0))]); + let out = run(vec![]); + let thumbnail = out.shapes.iter().any(|c| matches!(&c.shape, Shape::Mesh(m) if m.texture_id != egui::TextureId::default())); + assert!(thumbnail, "the chip draws the source document's thumbnail of Leaf"); +} + #[test] fn a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -11161,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 2df5067aa9..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"; @@ -188,9 +230,9 @@ const INLINE_FIELD_WIDTH: f32 = 80.0; /// The keys and labels of the Control bar's inline X/Y/W/H fields, in their order. const INLINE_FIELDS: [(&str, &str); 4] = [("x", "X:"), ("y", "Y:"), ("width", "W:"), ("height", "H:")]; -/// The label of an inline X/Y/W/H field. +/// The label of an inline X/Y/W/H field, underlined: a click on it opens the Transform panel. fn inline_label(t: &Tokens, lbl: &str) -> egui::RichText { - egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim) + egui::RichText::new(tl!(lbl)).size(12.0).color(t.text).underline() } /// The room the Control bar's inline X/Y/W/H fields take: their labels as drawn in the current @@ -203,6 +245,53 @@ fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 { labels + fields + crate::panels::transform::CONSTRAIN_LINK_SIZE + ui.spacing().item_spacing.x * items as f32 } +/// The Control bar's inline X/Y/W/H fields for the selection's box `b`, rotated with rotated +/// objects: X/Y are its reference point on the page (or a symbol instance's registration point), +/// shared with the Transform panel, and W/H its own sides. Edits keep or move that point, and the +/// Transform panel's menu choice of objects, patterns or both applies to them. +fn inline_transform_fields(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, units: vectorcraft_doc::Unit, b: &vectorcraft_doc::OrientedBox) { + let reference = crate::panels::transform::panel_reference(app, ui, b); + let (refi, rp) = (reference.index, reference.point); + let origin = app.ruler_origin(); + let link = crate::panels::transform::proportional(app, ui); + let copy = crate::panels::transform::alt_enter_copies(app, ui); + let values = [(rp.x, origin.x), (rp.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; + // The W/H link sits between W and H, but is made after H so Tab goes from W + // straight to H and finds the link after it. + let mut link_room = None; + let mut labels = Vec::with_capacity(INLINE_FIELDS.len()); + for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { + if k == "height" { + link_room = Some(crate::panels::transform::constrain_link_room(ui)); + } + // A click on the label opens the Transform panel, as the Transform link does; a drag scrubs. + let label = widgets::field_panel_label(ui, inline_label(t, lbl)).on_hover_text(tl!("Transform options")); + let (id, shown) = (("cb", k), Some(v - offset)); + let set = if matches!(k, "width" | "height") { + widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + } else { + widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + }; + labels.push(label); + if let Some(nv) = set { + let params = match k { + "x" => json!({"x": reference.bounds_xy(nv + offset, 0.0).0, "reference": refi, "copy": copy}), + "y" => json!({"y": reference.bounds_xy(0.0, nv + offset).1, "reference": refi, "copy": copy}), + _ => json!({k: nv, "reference": refi, "proportional": link, "copy": copy}), + }; + crate::panels::transform::run_transform(app, "object.setBounds", params); + } + } + if let Some(room) = link_room { + let id = ui.scope_id().with("cb-constrain-link"); + crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); + } + // After the fields, which each take the label before them as their own. + for label in &labels { + crate::panels::transform::popover(app, label); + } +} + /// The size of the Control bar's Align, Distribute and area type vertical alignment buttons, and /// the height of its Align To menu. const BUTTON: f32 = 24.0; @@ -710,7 +799,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { stroke_panel::weight_field(app, ui, "cb-stroke", weight, WEIGHT_FIELD_WIDTH); if ui.available_width() < row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve { left_out(ui); - } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) { + } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref()) { app.run("stroke.set", json!({"profile": id})).ok(); } } else { @@ -988,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 { @@ -1036,38 +1127,11 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, return; } crate::panels::transform::link(app, ui); - // The bounding box, rotated with rotated objects: its centre and its own sides. let selection_box = app.selection_box(); if selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t) { left_out(ui); } else if let Some(b) = selection_box { - let c = b.center(); - let origin = app.ruler_origin(); - let link = crate::panels::transform::proportional(app, ui); - let copy = crate::panels::transform::alt_enter_copies(app, ui); - let values = [(c.x, origin.x), (c.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; - // The W/H link sits between W and H, but is made after H so Tab goes from W - // straight to H and finds the link after it. - let mut link_room = None; - for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { - if k == "height" { - link_room = Some(crate::panels::transform::constrain_link_room(ui)); - } - widgets::field_label(ui, inline_label(t, lbl)); - let (id, shown) = (("cb", k), Some(v - offset)); - let set = if matches!(k, "width" | "height") { - widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - } else { - widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - }; - if let Some(nv) = set { - app.run("object.setBounds", json!({k: nv + offset, "reference": 4, "proportional": link, "copy": copy})).ok(); - } - } - if let Some(room) = link_room { - let id = ui.scope_id().with("cb-constrain-link"); - crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); - } + inline_transform_fields(app, ui, t, units, &b); } // Select Similar Objects comes last: it takes only the room every control ahead of it left. trailing_select_similar(app, ui); 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/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 9278b8baf3..f88372e75b 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -364,8 +364,10 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { ui.painter().rect_filled(crumb_rect, 3.0, t.hover); } if resp.clicked() { - if crumb.is_layer { - nav_cmd = Some(("object.exitIsolation", json!({}))); + // The top-level layer's crumb leaves isolation mode; a sublayer's or a group's + // crumb isolates that level. + if crumb.is_layer && i == 0 { + nav_cmd = Some(("object.exitIsolation", json!({ "all": true }))); } else if let Some(target) = crumb.id { nav_cmd = Some(("object.isolate", json!({ "id": target.0 }))); } @@ -401,7 +403,8 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if bresp.clicked() { pattern_cmd = pattern_cmd.or(pattern_edit.as_ref().map(|_| "object.pattern.done")); if pattern_cmd.is_none() { - // Up one level: the isolated object's parent, or out of isolation mode from a layer. + // Up one level: the isolated object's parent group, or `object.exitIsolation`, which + // goes from an isolated sublayer to its parent layer and otherwise leaves isolation mode. nav_cmd = Some(match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 03c7347704..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. @@ -1916,6 +1969,45 @@ fn isolation_bar_navigation_and_back_button_steps_up() { assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2))); } +/// With a sublayer isolated, the back arrow goes up one layer at a time and then leaves isolation +/// mode. The top-level layer's crumb leaves isolation mode from any depth, and a parent sublayer's +/// crumb isolates that sublayer. +#[test] +fn isolation_bar_back_button_steps_up_through_sublayers() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let top = app.session.active().unwrap().doc.layers[0].id; + let mid = NodeId(app.run("layer.newSublayer", json!({"parent": top.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap()); + let deep = NodeId(app.run("layer.newSublayer", json!({"parent": mid.0, "name": "Sublayer C"})).unwrap()["id"].as_u64().unwrap()); + app.run("layer.setCurrent", json!({"id": deep.0})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let ctx = isolation_bar_context(); + let click = |app: &mut crate::VectorcraftApp, pos: egui::Pos2| isolation_bar_gesture(app, &ctx, pos, pos); + let back = egui::pos2(15.0, 12.0); + let isolation = |app: &crate::VectorcraftApp| app.session.active().unwrap().isolation; + + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + let steps = app.session.doc().unwrap().history.undo.len(); + click(&mut app, back); + assert_eq!(isolation(&app), Some(mid), "back from the deepest sublayer"); + click(&mut app, back); + assert_eq!(isolation(&app), Some(top), "back from the middle sublayer"); + click(&mut app, back); + assert_eq!(isolation(&app), None, "back from the top-level layer"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "no undo step"); + + // "Layer 1" is the first crumb, at x 30 to about 75. + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + click(&mut app, egui::pos2(40.0, 12.0)); + assert_eq!(isolation(&app), None, "the top-level layer's crumb"); + + // "Sublayer B" is the second crumb, from about x 95. + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + click(&mut app, egui::pos2(115.0, 12.0)); + assert_eq!(isolation(&app), Some(mid), "the parent sublayer's crumb"); +} + /// Headless frames of the isolation bar over a 1200 × 700 canvas for one pointer gesture: a press /// at `from`, a move to `to` and a release there. `from == to` is a click. fn isolation_bar_gesture(app: &mut crate::VectorcraftApp, ctx: &egui::Context, from: egui::Pos2, to: egui::Pos2) { @@ -4653,3 +4745,59 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { assert!(groups_seen.iter().all(|s| *s), "{count} objects: a wide bar shows every group: {groups_seen:?}"); } } + +/// A click on the Control bar's X:, Y:, W: or H: label opens the Transform panel in a popover under +/// it, as the Transform link does, and a second click closes it. The click leaves the selection and +/// its bounds as they were, and no field takes the keyboard. A drag on W: still scrubs the width and +/// opens nothing. +#[test] +fn the_control_bars_x_y_w_and_h_labels_open_the_transform_panel() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2000.0, 600.0)); + let frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame_in(app, &ctx, screen, events); + let state = |app: &crate::VectorcraftApp| { + let st = app.session.active().unwrap(); + let b = st.doc.bounds_of(&st.selection.objects, false).unwrap(); + (st.selection.objects.len(), [b.x0, b.y0, b.x1, b.y1]) + }; + // The label's own node: a label whose text is `name` (the field it names is named the same). + let label = |nodes: &[egui::accesskit::Node], name: &str| { + let n = nodes.iter().find(|n| n.role() == egui::accesskit::Role::Label && n.value() == Some(name)); + let b = n.and_then(|n| n.bounds()).unwrap_or_else(|| panic!("no {name} label")); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + // The Transform panel's Rotate field is not on the bar itself. + let open = |nodes: &[egui::accesskit::Node]| nodes.iter().any(|n| n.label() == Some("Rotate")); + let before = state(&app); + frame(&mut app, vec![]); + for name in ["X:", "Y:", "W:", "H:"] { + let nodes = frame(&mut app, vec![]); + assert!(!open(&nodes), "{name}: the Transform panel is closed at first"); + let at = label(&nodes, name); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(open(&frame(&mut app, vec![])), "{name}: a click on the label opens the Transform panel"); + assert_eq!(ctx.memory(|m| m.focused()), None, "{name}: no field took the keyboard"); + assert_eq!(state(&app), before, "{name}: the selection and its bounds stay"); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(!open(&frame(&mut app, vec![])), "{name}: a second click closes it"); + } + let at = label(&frame(&mut app, vec![]), "W:"); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + for i in 1..=4 { + frame(&mut app, vec![egui::Event::PointerMoved(at + egui::vec2(5.0 * i as f32, 0.0))]); + } + frame(&mut app, vec![press_at(at + egui::vec2(20.0, 0.0), false)]); + let nodes = frame(&mut app, vec![]); + assert!(!open(&nodes), "a drag on W: opens nothing"); + let (_, [x0, _, x1, _]) = state(&app); + assert!(x1 - x0 > before.1[2] - before.1[0], "a drag on W: scrubs the width: {:?} to {:?}", before.1, [x0, x1]); +} 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/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 82ad6fd89d..11b8bbe145 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -1121,6 +1121,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_space((middle - BUTTON / 2.0 * row.len() as f32 - ui.cursor().min.x).max(0.0)); for &(s, slot) in row { let Some((rect, shown)) = slot_button(ui, &t, &press, slot, &mut actions) else { continue }; + crate::palette::note_spot(ui, rect, || crate::palette::SpotAt::Slot(Some(bar.name.clone()), slot.clone())); if edit_this { buttons.push((s, rect)); } @@ -1382,7 +1383,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect(); let heading = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).size(12.0).color(t.text_strong)); if !held.is_empty() { - heading(ui, &format!("{}:", tl!("Remove Tool"))); + heading(ui, &crate::i18n::colon(tl!("Remove Tool"))); for tool in held.iter().filter_map(|id| tool_info(id)) { if widgets::menu_item(ui, tool.label, true, false) { actions.push(Action::RemoveTool(bar.name.clone(), tool.id)); @@ -1391,7 +1392,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & ui.separator(); } for (cat, tools) in crate::edit_toolbar::sections() { - heading(ui, &format!("{}:", tl!(cat))); + heading(ui, &crate::i18n::colon(tl!(cat))); for tool in tools { if widgets::menu_item(ui, tool.label, !held.contains(&tool.id), false) { actions.push(Action::AddTool(bar.name.clone(), tool.id)); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b6a5d26cff..9e9c4e6816 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; @@ -80,6 +82,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; @@ -343,6 +346,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, @@ -398,6 +402,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, @@ -442,6 +447,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, @@ -472,12 +478,14 @@ 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, RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, + SmoothBridge: [crate::addons::pathtools::bridge::KIND] => crate::addons::pathtools::bridge::SPEC, TangentCircle: [crate::addons::pathtools::tangent_circle::KIND] => crate::addons::pathtools::tangent_circle::SPEC, SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, @@ -539,15 +547,16 @@ 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"], - // The view, zoom, download speed, selected color table entry and the preset name being typed. - Some(DialogKind::SaveForWeb) => &["__color", "__kbps", "__presetName", "__view", "__zoom"], + // The view, zoom, download speed, selected color table entries, the color table entry whose + // Color Picker opens and the preset name being typed. + Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__editColor", "__kbps", "__presetName", "__view", "__zoom"], // The link that keeps width and height in proportion. Some(DialogKind::Shape | DialogKind::TransformEach) => &["__constrain"], // The attention filter, the Keys section, the search text and the key being recorded. @@ -599,7 +608,8 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// Options setting set this way for several rows is sent to every row (Template also sets Lock /// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as /// one picked from its menu does, and the preset it shows follows the DXF options set this way. -/// A Graph Data Column Width set this way sets every column, as Cell Style's does. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. An Import PDF +/// `allPages` set this way to the other pick sets Import PDF pages as links back to its default. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -610,18 +620,30 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == layer_options::KIND { layer_options::note_set(d, &field, &value); } + if d.kind == import_pdf::KIND { + import_pdf::note_set(d, &field, &value); + } if d.kind == "preferences" { crate::prefs_dialog::note_set(d, &field, &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); } @@ -648,6 +670,16 @@ fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogRes r } +/// Set a tool's options with `tool.setOption` (`params`) and close the dialog; when the tool +/// refuses one of them, nothing is set and the dialog stays open. +fn set_tool_options_and_close(app: &mut VectorcraftApp, params: Value) -> DialogResult { + let r = app.run("tool.setOption", params); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// The field of a dialog opened over another (Import Shortcut Set over Keyboard Shortcuts) that /// holds the dialog under it, which Cancel and Escape show again. pub(crate) const PARENT: &str = "__parent"; @@ -662,8 +694,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); @@ -675,6 +708,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(()); @@ -710,6 +746,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(); @@ -831,6 +870,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let focus_first = focus_first && !clicked; let spec = spec(&d.kind); + // Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to. + if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) { + modal::over_parent(ctx); + } if let Some(window) = spec.window { return window(app, ctx); } @@ -873,14 +916,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if focus_first { ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); } + // When the dialog is taller than the window, its body scrolls, and the heading and the + // buttons stay in view. if let Some(body) = spec.body_with_actions { - match body(app, ui, &mut d) { + match modal::body_rows(ui, |ui| body(app, ui, &mut d)) { DialogAction::None => {} DialogAction::Confirm => ok = true, DialogAction::Cancel => cancel = true, } } else { - cancel = (spec.body)(app, ui, &mut d); + cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d)); } // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { @@ -1014,6 +1059,8 @@ mod tests_plugin_import; #[cfg(test)] mod tests_raster_formats; #[cfg(test)] +mod tests_raster_supplied_options; +#[cfg(test)] mod tests_svg_options_range; #[cfg(test)] @@ -1059,6 +1106,9 @@ mod tests_perspective; #[cfg(test)] mod tests_modal; +#[cfg(test)] +mod tests_scroll; + #[cfg(test)] mod tests_rectangular_grid; 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/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 62d4a2e368..64ea036fa2 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -9,7 +9,7 @@ //! open). //! Scatter: per value (`size`, `spacing`, `scatter` %, `rotation` °) `…Min`, `…Max` and `…Mode` //! (`fixed` | `random` | `pressure` | `tilt` | `bearing` | `rotation`), `rotationRelativeTo` (`page` | -//! `path`). +//! `path`), `hueJitter` (°). //! Art: `width` (%), `widthMode` (`fixed` | `pressure` | `tilt` | `bearing` | `rotation`), //! `widthMax` (the width at the heaviest pen pressure, upright or at 180°, %), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and //! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`, @@ -187,6 +187,7 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map) { f.insert(mode_key(key), json!(mode.id())); } f.insert("rotationRelativeTo".into(), json!(if s.rotation_relative_to_path { "path" } else { "page" })); + f.insert("hueJitter".into(), json!(s.hue_jitter)); } BrushKind::Art(a) => { let (mode, start, end) = match a.scale { @@ -268,6 +269,7 @@ pub(super) fn params(d: &Dialog) -> Value { p[*key] = json!([clamped(d, &min_key(key), range), clamped(d, &max_key(key), range)]); } p["modes"] = json!(SCATTER.map(|(key, _)| scatter_mode(d, key).id())); + p["hue_jitter"] = json!(clamped(d, "hueJitter", Scatter::HUE_JITTER_RANGE)); p } "art" => { @@ -457,6 +459,9 @@ fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(4.0); let relative = [("page", tl!("Page")), ("path", tl!("Path"))]; super::form::choice(ui, d, "rotationRelativeTo", tl!("Rotation relative to:"), (LABEL_W, 104.0), &relative); + ui.add_space(4.0); + // Each copy turns its colors' hue by its own amount up to this many degrees either way. + widgets::label_row(ui, tl!("Hue Jitter:"), LABEL_W, |ui| number(ui, d, "hueJitter", Scatter::HUE_JITTER_RANGE, "°", true)); } fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 670396947c..de59668708 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -153,6 +153,7 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { "Random", "Rotation relative to:", "Page", + "Hue Jitter:", "Colorization", "Method:", "Tints", @@ -163,10 +164,11 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.f64("sizeMin", 0.0), d.f64("sizeMax", 0.0), d.str("sizeMode")), (60.0, 140.0, "random".into())); assert_eq!((d.str("rotationRelativeTo"), d.str("colorization")), ("page".into(), "tints".into())); - // Values are kept within their ranges (rotation here); Fixed takes the first value. + assert_eq!(d.f64("hueJitter", -1.0), 0.0); + // Values are kept within their ranges (rotation and hue jitter here); Fixed takes the first value. set( &mut app, - json!({"sizeMode": "fixed", "sizeMin": 5000, "spacingMode": "pressure", "rotationMin": -400, "rotationRelativeTo": "path", "colorization": "hueShift"}), + json!({"sizeMode": "fixed", "sizeMin": 5000, "spacingMode": "pressure", "rotationMin": -400, "rotationRelativeTo": "path", "colorization": "hueShift", "hueJitter": 400}), ); assert!(shown(&mut app).contains("Hue Shift")); super::super::confirm(&mut app).unwrap(); @@ -177,12 +179,14 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { (&json!([5000.0, 140.0]), &json!(-180.0), &json!(["fixed", "pressure", "random", "random"])) ); assert_eq!((&def["rotation_relative_to_path"], &def["colorization"]["method"]), (&json!(true), &json!("hueShift"))); + assert_eq!(def["hue_jitter"], json!(180.0)); assert!(def["colorization"]["key"].is_object(), "the art's colour as the key: {def}"); assert!(drawn_height(&app, id) > before, "the stroke redraws with the bigger confetti"); // Opened again, it shows what was set. app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap(); let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.str("sizeMode"), d.str("spacingMode"), d.str("colorization")), ("fixed".into(), "pressure".into(), "hueShift".into())); + assert_eq!(d.f64("hueJitter", 0.0), 180.0); } #[test] diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 02515a3b89..c07f7af647 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); @@ -1073,7 +1074,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index bb3a5633ed..758832cd92 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -293,6 +293,19 @@ pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog ); d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); store(&mut d, &Picked::of(colour)); + d.fields.insert(crate::screen_color::PICKER_ID.into(), json!(crate::screen_color::picker_id())); + d +} + +/// The entry of the dialog's color list that a Color Picker opened with [`over_list_entry`] sets. +const COLOUR_INDEX: &str = "__colourIndex"; + +/// The Color Picker over the dialog `parent`, on `colour`, that sets entry `index` of the dialog's +/// list of colors `field` (Document Setup's `gridColors`) with its OK and goes back to it, leaving +/// the other entries as they are. Cancel goes back to `parent` as it was. It previews nothing. +pub(super) fn over_list_entry(parent: &Dialog, field: &str, index: usize, colour: Color) -> Dialog { + let mut d = over_effect(parent, field, colour); + d.fields.insert(COLOUR_INDEX.into(), json!(index)); d } @@ -371,6 +384,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let p = picked(d); let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color); let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color); + super::modal::fits_itself(ui); let (side, values_w, button_w, stacked) = layout_size(ui); let field_w = side + SLIDER_GAP + SLIDER_W; let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w }; @@ -749,7 +763,20 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(field) = d.fields.get(COLOUR_FIELD).and_then(Value::as_str) { let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; - parent.fields.insert(field.to_string(), json!(picked(d).color.to_hex())); + let hex = json!(picked(d).color.to_hex()); + match d.fields.get(COLOUR_INDEX) { + None => { + parent.fields.insert(field.to_string(), hex); + } + Some(index) => { + let entry = index + .as_u64() + .and_then(|i| usize::try_from(i).ok()) + .and_then(|i| parent.fields.get_mut(field)?.as_array_mut()?.get_mut(i)) + .ok_or("no such color")?; + *entry = hex; + } + } // The dialog previews the new colour when it comes back: end this picker's interaction, as // Cancel does, so the dialog starts its preview afresh. let _ = app.session.cancel_interaction(); diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 0786df7ca9..15344a131c 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -670,7 +670,8 @@ fn warnings_fit_below_the_preview_without_widening_the_dialog() { } let after = ctx.memory(|m| m.area_rect(id)).unwrap(); assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}"); - click_at(&ctx, &mut app, warnings[1].center()); + // The cube icon left of the web correction corrects the color too. + click_at(&ctx, &mut app, warnings[1].center() - vec2(19.0, 0.0)); assert!(is_web_safe(&picked(app.ui.dialog.as_ref().unwrap()).color), "web correction remains clickable"); } diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 3e95786f85..de7836f0a5 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -36,7 +36,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let mut rows = v.as_str() == Some("rows"); ui.add_space(4.0); egui::Grid::new("text-flow").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - let row = ui.label(egui::RichText::new(format!("{}:", tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); ui.label_inputs_by(row.id, |ui| { ui.horizontal(|ui| { if widgets::radio(ui, tl!("By Rows"), rows, true) { 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/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 140ace0fde..3a977e76c6 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -4,7 +4,7 @@ use super::DialogSpec; use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets}; use egui::{RichText, Ui}; use serde_json::{Value, json}; -use vectorcraft_doc::dimension::DimensionOptions; +use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions}; pub const KIND: &str = "dimensionOptions"; pub(super) const SPEC: DialogSpec = DialogSpec { @@ -32,6 +32,10 @@ const UNITS: Choices = &[ ]; const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")]; const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")]; +/// The style of each `ARROWS` entry, in the same order. +const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None]; +/// The size of an Arrow Style preview: a line with the head at its right end. +const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0); const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")]; const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")]; @@ -69,6 +73,29 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, l }); changed } +/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in +/// the open list and in the closed field. +fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map, id: &str) -> bool { + const KEY: &str = "arrowStyle"; + let mut changed = false; + widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| { + let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default(); + let shown = ARROWS.iter().position(|(v, _)| *v == current); + let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect(); + let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| { + if let Some(style) = ARROW_STYLES.get(i) { + crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink); + } + }; + if let Some((value, _)) = + widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i)) + { + fields.insert(KEY.into(), json!(value)); + changed = true; + } + }); + changed +} fn number(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, label: &str, range: (f64, f64), suffix: &str) -> bool { let mut changed = false; widgets::label_row(ui, tl!(label), 96.0, |ui| { @@ -160,7 +187,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { color(ui, f, "lineColor"); }); ui.horizontal(|ui| { - choose(ui, f, "arrowStyle", "Arrow Style:", ARROWS); + arrow_style(ui, f, "arrowStyle"); number(ui, f, "arrowScale", "Arrow Scale:", (1.0, 1000.0), "%"); }); }); @@ -211,7 +238,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { Ok(o) => { let sample = o.label(72.0, false).unwrap_or_default(); let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(format!("{}: {sample}", tl!("Preview (1 inch on the page)"))).color(t.text)); + ui.label(RichText::new(format!("{} {sample}", crate::i18n::colon(tl!("Preview (1 inch on the page)")))).color(t.text)); } Err(e) => { ui.colored_label(Tokens::get(ui.ctx()).text, e); @@ -310,7 +337,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { changed |= number(ui, &mut f, "lineWeight", "Line Weight:", (0.1, 100.0), "pt"); changed |= color(ui, &mut f, "lineColor"); }); - ui.horizontal(|ui| changed |= choose(ui, &mut f, "arrowStyle", "Arrow Style:", ARROWS)); + ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle")); ui.horizontal(|ui| { changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt"); changed |= color(ui, &mut f, "textColor"); @@ -377,4 +404,56 @@ mod tests { assert!(text.contains(label), "{label}: {text}"); } } + + /// Whether a frame drew a picture (a textured mesh) just before the text `name` on its line. + fn picture_before(out: &egui::FullOutput, name: &str) -> bool { + fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, pictures: &mut Vec) { + match s { + egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.visual_bounding_rect())), + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => pictures.push(m.calc_bounds()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, pictures)), + _ => {} + } + } + let (mut texts, mut pictures) = (vec![], vec![]); + for c in &out.shapes { + collect(&c.shape, &mut texts, &mut pictures); + } + texts + .iter() + .filter(|(t, _)| t == name) + .any(|(_, r)| pictures.iter().any(|p| p.max.x <= r.min.x + 1.0 && r.min.x - p.max.x < 16.0 && p.min.y < r.max.y && p.max.y > r.min.y)) + } + + /// The frame `f` draws, once its previews are loaded. + fn frame(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &mut Ui)) -> egui::FullOutput { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear(); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)) + } + + /// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead, + /// drawn, before its name (#8049). + #[test] + fn arrow_style_shows_a_drawn_arrowhead() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("tool.options", json!({"tool":"dimension"})).unwrap(); + let out = frame(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert!(picture_before(&out, "Filled"), "Tool Options"); + app.ui.dialog = None; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowStyle":"tick"}})).unwrap(); + let out = frame(&mut app, properties_section); + assert!(picture_before(&out, "Tick"), "Properties"); + } + + /// Each Arrow Style entry previews the style its value names. + #[test] + fn arrow_previews_follow_the_listed_styles() { + assert_eq!(ARROWS.len(), ARROW_STYLES.len()); + for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) { + assert_eq!(serde_json::to_value(style).unwrap(), json!(value)); + } + } } diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 1946cc86b2..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) { @@ -175,20 +193,88 @@ fn general(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool close } +/// The id of the Transparency tab's box that shows grid color `index` (0 or 1). +fn grid_color_box_id(index: usize) -> egui::Id { + egui::Id::unique(("grid-color-box", index)) +} + +/// 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); - let colors: 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(); + // A preset name in the fields (any case, as `document.setup` takes it) becomes the preset's two + // colors, which the hex fields and the Color Picker edit one at a time. + if let Some((_, pair)) = + d.fields.get("gridColors").and_then(Value::as_str).and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| p.eq_ignore_ascii_case(n))) + { + d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); + } + // 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| { @@ -196,25 +282,58 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); } }); - // The two colours (the first is also the paper colour): editing either makes them Custom. + // 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, 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 { let hex = colors.get(i).map_or("", |h| h.trim_start_matches('#')); + let colour = vectorcraft_color::Color::from_hex(hex); + let name = format!("{} {}", tl!("Grid Colors:"), i + 1); let (chip, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); - if let Some(c) = vectorcraft_color::Color::from_hex(hex) { + let resp = ui.interact(chip, grid_color_box_id(i), egui::Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + let keyed = resp.has_focus() + && ui.input_mut(|inp| { + inp.consume_key(egui::Modifiers::NONE, egui::Key::Space) | inp.consume_key(egui::Modifiers::NONE, egui::Key::Enter) + }); + if resp.clicked() || keyed { + pick = Some(i); + } + if resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + if let Some(c) = colour { ui.painter().rect_filled(chip, 2.0, crate::panels::c32(&c)); } ui.painter().rect_stroke(chip, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); - let name = format!("{} {}", tl!("Grid Colors:"), i + 1); + if resp.has_focus() { + 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 = colors.clone(); - 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 { + // 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); check(ui, d, "simulatePaper", tl!("Simulate Colored Paper")); ui.add_space(14.0); @@ -428,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] @@ -635,4 +799,387 @@ mod tests { assert_eq!(fill(&app, id), before); assert_eq!(undo_steps(&app), steps); } + + /// The Light pair a new document's transparency grid starts with. + const LIGHT: [&str; 2] = ["#ffffff", "#cccccc"]; + + fn hex(h: &str) -> Color { + Color::from_hex(h).unwrap_or_else(|| panic!("bad hex {h}")) + } + + /// The grid colors Document Setup `d` holds. + fn dialog_grid(d: &crate::state::Dialog) -> Vec { + d.fields["gridColors"].as_array().unwrap().iter().map(|c| hex(c.as_str().unwrap())).collect() + } + + /// A new document with Document Setup open on its Transparency tab, drawn in the context returned. + fn transparency_tab() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!("Transparency")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + for _ in 0..4 { + dialog_frame(&mut app, &ctx, vec![]); + } + (app, ctx) + } + + /// Clicks the box of grid color `index`. + fn click_grid_box(app: &mut VectorcraftApp, ctx: &egui::Context, index: usize) { + let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, ctx, vec![button(false)]); + } + + /// The Color Picker is open over Document Setup, on `color`, and Document Setup's OK has not run. + fn assert_picker_over_setup(app: &VectorcraftApp, color: &str, case: &str) { + let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{case}: no dialog")); + assert_eq!(d.kind, "colorPicker", "{case}"); + assert_eq!(d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), Some(hex(color)), "{case}"); + assert_eq!(crate::dialogs::parent(d).map(|p| p.kind), Some(super::KIND.to_string()), "{case}"); + assert_eq!(undo_steps(app), 0, "{case}: Document Setup's OK has not run"); + } + + /// A click on either grid color's box opens the Color Picker over Document Setup on that + /// color. Its OK sets only that color, the Grid Colors menu names the pair (Custom, or the + /// preset it matches), and Document Setup's OK applies the pair in one undo step. + #[test] + fn a_grid_color_box_opens_the_color_picker_and_its_ok_sets_that_color() { + for (index, picked, pair, name) in [(0, "#00ff00", ["#00ff00", "#cccccc"], "Custom"), (1, "#c4dcff", ["#ffffff", "#c4dcff"], "Blue")] { + let (mut app, ctx) = transparency_tab(); + click_grid_box(&mut app, &ctx, index); + assert_picker_over_setup(&app, LIGHT[index], name); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!(picked)); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{name}"); + assert_eq!(undo_steps(&app), 0, "{name}: the picker's OK leaves the document as it is"); + dialog_frame(&mut app, &ctx, vec![]); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == name), "{name}: {texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_colors, st.doc.setup.grid_colors_name()), (pair.map(hex), name)); + assert_eq!(undo_steps(&app), 1, "{name}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex), "{name}"); + } + } + + /// With the keyboard on a grid color's box, Enter or Space opens the Color Picker on that + /// color instead of pressing Document Setup's OK. + #[test] + fn enter_or_space_on_a_grid_color_box_opens_the_color_picker() { + for (index, key) in [(0, egui::Key::Enter), (1, egui::Key::Space)] { + let (mut app, ctx) = transparency_tab(); + ctx.memory_mut(|m| m.request_focus(super::grid_color_box_id(index))); + dialog_frame(&mut app, &ctx, vec![]); + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + dialog_frame(&mut app, &ctx, vec![press]); + assert_picker_over_setup(&app, LIGHT[index], &format!("{key:?}")); + } + } + + /// Cancel in the Color Picker goes back to Document Setup with the grid colors as they were, + /// and so does its OK on the color it opened on; Document Setup's OK then records no undo step. + #[test] + fn grid_color_picker_cancel_or_an_unchanged_ok_changes_nothing() { + for cancel in [true, false] { + let (mut app, ctx) = transparency_tab(); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, LIGHT[1], &format!("cancel {cancel}")); + if cancel { + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + crate::dialogs::cancel(&mut app); + } else { + crate::dialogs::confirm(&mut app).unwrap(); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, LIGHT.map(hex).to_vec()), "cancel {cancel}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors_name(), "Light"); + assert_eq!(undo_steps(&app), 0, "cancel {cancel}"); + } + } + + /// 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. + #[test] + fn a_grid_color_box_opens_the_picker_when_the_field_names_a_preset() { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!("blue")); + dialog_frame(&mut app, &ctx, vec![]); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, "#c4dcff", "blue"); + 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(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, ["#ffffff", "#00ff00"].map(hex).to_vec())); + } + + /// The screen color sampler works in the Color Picker of a grid color: the color sampled goes + /// to that picker, and its OK sets the grid color. + #[test] + fn the_grid_color_picker_takes_a_screen_sampled_color() { + let (mut app, ctx) = transparency_tab(); + let (tx, rx) = std::sync::mpsc::channel::(); + let mut rx = Some(rx); + app.services.screen_color = Some(Box::new(move || rx.take().ok_or_else(|| "shown twice".to_string()))); + click_grid_box(&mut app, &ctx, 0); + assert_picker_over_setup(&app, LIGHT[0], "before sampling"); + app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap(); + tx.send(Ok(Some([0.0, 0.5, 1.0]))).unwrap(); + crate::screen_color::poll(&mut app, &ctx); + let sampled = app.ui.dialog.as_ref().unwrap().fields.get("color").and_then(vectorcraft_engine::cmd::color_value).unwrap(); + assert_ne!(sampled.to_hex(), LIGHT[0]); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + let grid: Vec = dialog_grid(d).iter().map(Color::to_hex).collect(); + assert_eq!((d.kind.as_str(), grid), (super::KIND, vec![sampled.to_hex(), LIGHT[1].to_string()])); + } + + /// Clicks the hex field that shows `digits` and types `typed` over its text, leaving the edit + /// pending; returns the field's id. + fn type_into_hex_field(app: &mut VectorcraftApp, ctx: &egui::Context, digits: &str, typed: &str) -> egui::Id { + let texts = dialog_frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == digits).unwrap_or_else(|| panic!("no field {digits}: {texts:?}")).1.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, ctx, vec![button(false)]); + let field = ctx.memory(|m| m.focused()).unwrap_or_else(|| panic!("field {digits} has no focus")); + dialog_frame(app, ctx, vec![Event::Text(typed.into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit in {digits} is pending"); + field + } + + /// A click on a grid color's box whose press and release come in one frame, while that + /// color's hex field holds an edit, opens the Color Picker on the edited color: the press + /// commits the edit before the picker opens. The picker's unchanged OK keeps the edit, and the + /// other color stays as it was. + #[test] + fn a_grid_color_box_clicked_during_a_hex_edit_opens_the_picker_on_the_edit() { + for index in [0, 1] { + let (mut app, ctx) = transparency_tab(); + type_into_hex_field(&mut app, &ctx, LIGHT[index].trim_start_matches('#'), "123456"); + let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(&mut app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]); + let case = format!("box {index}"); + assert_picker_over_setup(&app, "#123456", &case); + let mut pair = LIGHT; + pair[index] = "#123456"; + assert_eq!(dialog_grid(&crate::dialogs::parent(app.ui.dialog.as_ref().unwrap()).unwrap()), pair.map(hex).to_vec(), "{case}"); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{case}"); + } + } + + /// A hex field's edit that commits in the frame a Grid Colors preset is chosen replaces only + /// its own color in the preset's pair: the other color is the preset's. The test gives the + /// field the focus while the Grid Colors menu is open, then chooses a preset with a click whose + /// press and release come in one frame. + #[test] + fn a_hex_edit_committed_with_a_preset_choice_keeps_the_presets_other_color() { + let field = { + let (mut app, ctx) = transparency_tab(); + type_into_hex_field(&mut app, &ctx, "ffffff", "123456") + }; + let (mut app, ctx) = transparency_tab(); + let click = |app: &mut VectorcraftApp, label: &str, frames: usize| { + let texts = dialog_frame(app, &ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label}: {texts:?}")).1.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + if frames == 1 { + dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]); + } else { + dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, &ctx, vec![button(false)]); + } + }; + click(&mut app, "Light", 2); + ctx.memory_mut(|m| m.request_focus(field)); + dialog_frame(&mut app, &ctx, vec![]); + let select_all = Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + dialog_frame(&mut app, &ctx, vec![select_all, Event::Text("123456".into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit is pending"); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == "123456") && texts.iter().any(|t| t == "Blue"), "{texts:?}"); + click(&mut app, "Blue", 1); + assert_eq!(dialog_grid(app.ui.dialog.as_ref().unwrap()), ["#123456", "#c4dcff"].map(hex).to_vec()); + } + + /// The picker's OK sets nothing when the dialog under it has no such color or is gone: it is + /// an error, and the picker stays open. + #[test] + fn grid_color_picker_without_its_color_or_its_dialog_is_an_error() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + let setup = app.ui.dialog.clone().unwrap(); + let mut short = setup.clone(); + short.fields.insert("gridColors".into(), json!(["#ffffff"])); + let mut orphan = crate::dialogs::color_picker::over_list_entry(&setup, "gridColors", 0, Color::WHITE); + orphan.fields.remove(crate::dialogs::PARENT); + for picker in [crate::dialogs::color_picker::over_list_entry(&short, "gridColors", 1, Color::WHITE), orphan] { + app.ui.dialog = Some(picker); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); + } + 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/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index e9ffdc681e..987fceeea4 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -322,6 +322,13 @@ fn center_round(x: f64) -> f64 { (x * 1e4).round() / 1e4 } +/// The value screen readers give Blur Center at `c` (0 to 1 of the bounds): Horizontal and +/// Vertical in percent, each label followed by the UI language's colon. +pub(super) fn blur_center_value(c: [f64; 2]) -> String { + let percent = |v: f64| (v * 1000.0).round() / 10.0; + format!("{} {}%, {} {}%", crate::i18n::colon(tl!("Horizontal")), percent(c[0]), crate::i18n::colon(tl!("Vertical")), percent(c[1])) +} + /// Radial Blur's Blur Center: a box standing for the object's bounds, with the blur's pattern (rays /// for Zoom, rings for Spin) drawn about the center. A press or a drag in the box puts the center /// there; with the keyboard focus the arrow keys move it 1 % of the box (10 % with Shift). The @@ -339,9 +346,8 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { let (rect, _) = ui.allocate_exact_size(egui::vec2(CENTER_BOX, CENTER_BOX), Sense::hover()); let id = ui.scope_id().with("radial-blur-center"); let resp = ui.interact(rect, id, Sense::click_and_drag()); - let percent = |v: f64| (v * 1000.0).round() / 10.0; let name = tl!("Blur Center").to_string(); - let value = format!("{}: {}%, {}: {}%", tl!("Horizontal"), percent(c[0]), tl!("Vertical"), percent(c[1])); + let value = blur_center_value(c); let enabled = ui.is_enabled(); resp.widget_info(|| egui::WidgetInfo { current_text_value: Some(value.clone()), @@ -396,7 +402,7 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { ui.vertical(|ui| { egui::Grid::new("blur-center-fields").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| { for (i, label) in ["Horizontal", "Vertical"].into_iter().enumerate() { - let row = ui.label(egui::RichText::new(format!("{}:", tl!(label))).color(t.text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!(label))).color(t.text)); ui.label_inputs_by(row.id, |ui| { if let Some(x) = widgets::range_field_named(ui, ("blur-center", i), None, c[i] * 100.0, 0.0..=100.0, &form::unit_suffix("%"), 1, 72.0) 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 9c374f3cf5..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, run_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()); @@ -155,12 +240,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { values.insert(key.into(), json!(d.bool(key))); } if let Some((cmd, params)) = command { + // Options the tool would refuse leave the dialog open, before the flare is accepted. + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create("flare").as_ref(), &values)?; // Accept the preview once; option persistence follows successful artwork creation. let result = form::commit_preview(app, &cmd, params)?; app.run("tool.setOption", json!({ "tool": "flare", "values": values }))?; Ok(result) } else { - run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "flare", "values": values })) } } @@ -312,10 +399,46 @@ mod tests { super::super::confirm(&mut app).unwrap(); let parts = flare_parts(&app); assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}"); - // Out-of-range values are kept within the option's range. - app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 900, "diameter": -4}})).unwrap(); - let o = app.session.tool_options_of("flare"); - assert_eq!((o["opacity"].as_f64(), o["diameter"].as_f64()), (Some(100.0), Some(0.0))); + // An out-of-range value is an error, and no option changes. + let before = app.session.tool_options_of("flare"); + let e = app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 50, "diameter": -4}})).unwrap_err(); + assert_eq!(e, "tool `flare`: `diameter` must be a number from 0 to 1000"); + 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] diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 733ff22398..b46f35a79f 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -111,7 +111,7 @@ fn lengths(kind: &str) -> &'static [&'static str] { /// number: fields that ↑/↓ step by one (Shift: ten) and that do math, as the distances do. fn suffix(kind: &str, key: &str) -> Option<&'static str> { match (kind, key) { - ("rotate" | "shear" | "reflect" | "move" | "lineSegment", "angle") => Some("°"), + ("rotate" | "shear" | "reflect" | "move" | "lineSegment", "angle") | ("shear", "axisAngle") => Some("°"), ("scale", "sx" | "sy") | ("spiral", "decay") => Some("%"), _ => None, } @@ -138,6 +138,7 @@ fn order(kind: &str) -> &'static [&'static str] { "spiral" => &["radius", "decay", "segments"], "artboardOptions" => &["name", "width", "height"], "lineSegment" => &["length", "angle"], + "shear" => &["angle", "axis", "axisAngle"], _ => &[], } } @@ -163,8 +164,7 @@ fn choices(kind: &str, key: &str) -> Vec<(&'static str, &'static str)> { match (kind, key) { ("offsetPath", "joins") => vec![("miter", tl!("Miter")), ("round", tl!("Round")), ("bevel", tl!("Bevel"))], ("average", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("both", "Both")], - ("reflect", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("angle", "Angle")], - ("shear", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical")], + ("reflect" | "shear", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("angle", "Angle")], _ => vec![], } } @@ -368,11 +368,19 @@ pub(super) fn grid_then(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, more: imp if lengths.contains(&k.as_str()) { length_field(ui, d, &k, &humanized(&k), unit); } else if let Some(suffix) = suffix(&d.kind, &k) { - let row = row_label(ui, &humanized(&k)); + let label = match (d.kind.as_str(), k.as_str()) { + ("shear", "axisAngle") => tl!("Axis Angle").into(), + _ => humanized(&k), + }; + // Shear's Axis Angle is the axis while the Angle axis is chosen, and keeps its value otherwise. + let enabled = d.kind != "shear" || k != "axisAngle" || d.str("axis") == "angle"; + let row = row_label(ui, &label); ui.label_inputs_by(row.id, |ui| { - if let Some(v) = crate::widgets::plain_field(ui, ("dlg-num", &k), d.f64(&k, 0.0), suffix, 3, FIELD_W) { - d.fields.insert(k, json!(v)); - } + ui.add_enabled_ui(enabled, |ui| { + if let Some(v) = crate::widgets::plain_field(ui, ("dlg-num", &k), d.f64(&k, 0.0), suffix, 3, FIELD_W) { + d.fields.insert(k, json!(v)); + } + }); }); ui.end_row(); } else if let Some(ends) = skew_ends(&d.kind, &k) { @@ -843,11 +851,17 @@ pub(crate) fn humanize(k: &str) -> String { } } -/// [`humanize`] translated where it is painted: the ":" stays outside the translated text. +/// A style attribute as the style dialogs list it: the [`humanized`] key, then its value. +pub(super) fn attribute_line(key: &str, value: &Value) -> String { + format!("{} {value}", humanized(key)) +} + +/// [`humanize`] translated where it is painted: the ":" stays outside the translated text and is +/// written as the UI language writes a label's colon ([`crate::i18n::colon`]). pub(super) fn humanized(k: &str) -> String { let h = humanize(k); match h.strip_suffix(':') { - Some(base) => format!("{}:", tl!(base)), + Some(base) => crate::i18n::colon(tl!(base)), None => tl!(&h).to_string(), } } diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 93e3a1c2ff..aa793afef2 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -21,7 +21,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_brush::Variation; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -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,25 +332,68 @@ 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; -/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness and a line along -/// its long axis, and beside it three dabs of the tip, the middle one darker. A click or a drag in -/// the square points the Angle at the pointer and gives the square the keyboard focus; screen -/// readers get it as the Angle slider, and its keys step the Angle as a dialog slider's do -/// ([`widgets::stepped_area`]) within -180° to 180°. -fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { +/// 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 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 `min_roundness` to 100% as a dialog slider's do +/// ([`widgets::stepped_area`]). +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)); + let center = square.center(); let response = ui.interact(square, ui.scope_id().with("freehand-tip-angle"), egui::Sense::click_and_drag()); + // 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| { + 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() { + let pressed = ui.input(|i| i.pointer.press_origin()).is_some_and(|p| near_dot(p, d)); + ui.data_mut(|m| m.insert_temp(on_dot, pressed)); + started = Some(pressed); + } + // A click whose press and release came in the same frame: its press is among this frame's events. + let dot_drag = started.unwrap_or_else(|| { + let press = ui.input(|i| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos), + _ => None, + }) + }); + response.clicked() && press.is_some_and(|p| near_dot(p, d)) + }); + if !response.is_pointer_button_down_on() { + ui.data_mut(|m| m.remove_temp::(on_dot)); + } if let Some((p, _)) = widgets::pointer_phase(&response) { - let delta = p - square.center(); - if delta.length_sq() > 1.0 { + let delta = p - center; + if dot_drag { + 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())); } } + if dot_drag && response.is_pointer_button_down_on() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } else if response.hover_pos().is_some_and(|p| near_dot(p, d)) && !response.is_pointer_button_down_on() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } let painter = ui.painter_at(rect); painter.rect_filled(square, 2.0, t.input); painter.rect_stroke(square, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); @@ -358,12 +402,18 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { if let Some(a) = widgets::stepped_area(ui, &response, tl!("Angle"), Some(shown)) { d.fields.insert("angle".into(), json!(a)); } - let a = d.f64("angle", 0.0).clamp(-180.0, 180.0).to_radians(); - // The long axis on screen (y down: a positive angle tilts it up to the right) and the short one. - let u = egui::vec2(a.cos() as f32, -a.sin() as f32); - let v = egui::vec2(-u.y, u.x); - let long = 18.0; - let short = long * blob_tip_short_ratio(d.f64("roundness", 100.0)); + // The Roundness slider takes the focus and the keys only: the square's response reads the pointer. + let roundness = ui.interact(square, ui.scope_id().with("freehand-tip-roundness"), egui::Sense::focusable_noninteractive()); + 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), 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) = tip_axes(d.f64("angle", 0.0)); + let long = TIP_LONG; + 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| { @@ -373,25 +423,54 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { .collect(); painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); }; - let center = square.center(); dab(center, t.text); - painter.line_segment([center, center + u * 25.0], egui::Stroke::new(1.0, t.accent)); + painter.line_segment([center, center + u * 22.0], egui::Stroke::new(1.0, t.accent)); + 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 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; for (i, color) in [t.text_dim, t.text, t.text_dim].into_iter().enumerate() { dab(egui::pos2(strip + i as f32 * 1.5 * long, center.y), color); } } +/// 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 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)) +} + +/// 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 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 `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) } /// OK: set the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 3a73d6f3bb..e324bbbd45 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -28,11 +28,70 @@ fn blob_tip_fields_confirm_and_cancel() { assert_eq!(app.session.tool_options_of("blobBrush")["roundness"], json!(0.0)); } +/// OK with a Fidelity the Smooth tool refuses shows the error and keeps the dialog open, with +/// nothing set; a Fidelity it takes then closes it. +#[test] +fn a_refused_fidelity_keeps_the_dialog_open() { + let mut app = app(); + app.run("tool.options", json!({"tool": "smooth"})).unwrap(); + let before = app.session.tool_options_of("smooth"); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(0.01)); + let e = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(e, "tool `smooth`: `fidelity` must be a number from 0.05 to 100"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + assert_eq!(app.session.tool_options_of("smooth"), before); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of("smooth")["fidelity"], json!(5.0)); +} + #[test] 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}"); + } +} + +/// A Roundness dot of the tip preview gives its distance from the center along the tip's short +/// axis as a percentage of half the tip's length, on either side and at any Angle: 0% at the +/// center, 100% at half the length and past it. A move along the long axis leaves it as it is, and +/// the dots drawn for a Roundness give that Roundness back. +#[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) = 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!(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] = 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!(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"); + } } } diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 838ba066d9..766ae898ee 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -577,9 +577,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// `text` with the colon of a field label. +/// `text` with the colon of a field label, as the UI language writes it. fn colon(text: &str) -> String { - format!("{text}:") + crate::i18n::colon(text) } /// A checkbox bound to `d.fields[key]`, dimmed while the type picked has no use for it. @@ -977,6 +977,22 @@ mod tests { assert!(app.ui.dialog.is_none()); } + /// Field labels end in the UI language's colon: in French a no-break space and a colon (#7991). + #[test] + fn field_labels_use_the_language_colon() { + let mut app = app_with_graph("column"); + crate::menus::invoke(&mut app, COMMAND, json!({})); + set(&mut app, PAGE, json!("valueAxis")); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let mut h = harness(app); + h.run_steps(3); + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, "Suffix")); + let found = h.query_by_role_and_label(Role::TextInput, &want).is_some(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(found, "a text field named {want:?}"); + } + /// A Type button changes the graph's type and keeps its data. #[test] fn a_type_button_changes_the_graph_type_and_keeps_its_data() { diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 4ef8c925d8..bedd3387c2 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -3,7 +3,10 @@ //! //! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the //! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for -//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set +//! a file read from a path and opened without a password; `null` until it is checked or cleared, +//! when it follows the pages picked: on for All, off for a range; picking the other of All and +//! Range sets it back to `null`; `__linkable` is false for a file `linkPages` does not take, such as +//! one over its size limit), `cropTo` and `password`. `__locked` is set //! until the password is accepted: OK then unlocks the file, and with `__passwordOnly` (Place with //! Show Import Options off) places its first page at once. `__place` keeps the other `file.place` //! params (Link, Template, `at`…). The file's bytes stay out of the fields, in @@ -144,10 +147,11 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Option { } /// Can the pages open linked: the file was read from a path (a linked page is read from its -/// file again) and opens without a password (`document.open`'s `linkPages` refuses one). +/// file again), `document.open`'s `linkPages` takes its size, and it opens without a password +/// (`linkPages` refuses one). fn can_link(d: &Dialog) -> bool { - d.fields.get("path").and_then(Value::as_str).is_some() && password(d).is_none() + d.fields.get("path").and_then(Value::as_str).is_some() && d.bool("__linkable") && password(d).is_none() +} + +/// Import PDF Pages as Links as checked or cleared, or, when it is `null`, as the pages picked +/// default it: on for All, off for a range. +fn link_pages(d: &Dialog) -> bool { + d.fields.get("linkPages").and_then(Value::as_bool).unwrap_or_else(|| d.bool("allPages")) } /// Import PDF Pages as Links is checked, and can be. -fn links_on(d: &Dialog) -> bool { - d.bool("linkPages") && can_link(d) +pub(super) fn links_on(d: &Dialog) -> bool { + link_pages(d) && can_link(d) +} + +/// Picks All (true) or Range. A change of pick sets Import PDF Pages as Links back to that pick's +/// default; picking the one already picked keeps the box as it is. +fn pick_all_pages(d: &mut Dialog, all: bool) { + if d.bool("allPages") != all { + d.fields.insert("allPages".into(), json!(all)); + d.fields.insert("linkPages".into(), Value::Null); + } +} + +/// Records that `ui.dialog.set` sets `field` to `value`: a change of `allPages` sets Import PDF +/// Pages as Links back to its default, as a click on All or Range does. +pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) { + if field == "allPages" + && let Some(all) = value.as_bool() + { + pick_all_pages(d, all); + } } /// OK: unlock the file with the password, else open the pages or place the page. @@ -330,20 +360,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.label(egui::RichText::new(tl!("Pages")).color(t.text)); let all = d.bool("allPages"); if widgets::radio(ui, tl!("All"), all, true) { - d.fields.insert("allPages".into(), json!(true)); + pick_all_pages(d, true); } ui.horizontal(|ui| { if widgets::radio(ui, tl!("Range:"), !all, true) { - d.fields.insert("allPages".into(), json!(false)); + pick_all_pages(d, false); } if super::form::text_edit_named(ui, d, "range", tl!("Range:"), 90.0).gained_focus() { - d.fields.insert("allPages".into(), json!(false)); + pick_all_pages(d, false); } }); widgets::dim_label(ui, tl!("e.g. 1-3, 5")); ui.add_space(10.0); if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) { - d.fields.insert("linkPages".into(), json!(!d.bool("linkPages"))); + d.fields.insert("linkPages".into(), json!(!link_pages(d))); } } }); diff --git a/crates/ui-egui/src/dialogs/liquify.rs b/crates/ui-egui/src/dialogs/liquify.rs index 40aa677f17..18b8e48418 100644 --- a/crates/ui-egui/src/dialogs/liquify.rs +++ b/crates/ui-egui/src/dialogs/liquify.rs @@ -12,7 +12,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_tools::distort::liquify::LiquifyKind; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -145,7 +145,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { values.insert(key.into(), json!(d.f64(key, 0.0) / 100.0)); } } - run_and_close(app, "tool.setOption", json!({ "tool": kind(d).id(), "values": values })) + set_tool_options_and_close(app, json!({ "tool": kind(d).id(), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_bucket.rs b/crates/ui-egui/src/dialogs/live_paint_bucket.rs index f515c3d904..11bdcf5c41 100644 --- a/crates/ui-egui/src/dialogs/live_paint_bucket.rs +++ b/crates/ui-egui/src/dialogs/live_paint_bucket.rs @@ -15,7 +15,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -86,7 +86,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_selection.rs b/crates/ui-egui/src/dialogs/live_paint_selection.rs index a1a91ad2b7..95584c2f96 100644 --- a/crates/ui-egui/src/dialogs/live_paint_selection.rs +++ b/crates/ui-egui/src/dialogs/live_paint_selection.rs @@ -13,7 +13,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -80,7 +80,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index f72383068e..950f28d6e4 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -2,8 +2,9 @@ //! window with no title bar that opens centred and moves by dragging its heading (the band from its //! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where //! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows -//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons -//! stay in view. +//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its +//! heading and buttons stay in view. A window without such rows that is still too tall or too wide +//! for the screen scrolls as a whole on that axis. use egui::{Id, Rect, Vec2}; @@ -25,6 +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 opened = opened(ctx, id); let shown = egui::Window::new(title) .id(id) .order(egui::Order::Foreground) @@ -33,17 +35,117 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .title_bar(false) .anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial)) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin))) - .show(ctx, add)?; - keep_rest(ctx, id, shown.response.rect.height()); + .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.data_mut(|m| { + m.insert_temp(id.with(TOP_ROWS_KEY), true); + m.insert_temp(id.with(TOP_WHOLE_KEY), true); + }); + } + // A window whose contents are wider than the screen has room for, or taller without + // rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis, + // so none of it is out of reach. The contents keep their ids whether the window scrolls + // or not, so a field being edited keeps its text when that changes. + let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default(); + let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents")); + let (r, contents) = if wide || tall { + let room = whole_room(ctx, margin); + let mut area = egui::ScrollArea::new([wide, tall]); + if ctx.data_mut(|m| m.remove_temp::(id.with(TOP_WHOLE_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let out = area + .id_salt("modal-whole") + .max_width(room.x) + .max_height(room.y) + .min_scrolled_width(room.x) + .min_scrolled_height(room.y) + .show(ui, |ui| ui.scope_builder(scope, add).inner); + (out.inner, out.content_size) + } else { + let r = ui.scope_builder(scope, add).inner; + (r, ui.min_rect().size()) + }; + ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents)); + r + })?; + keep_rest(ctx, id, shown.response.rect.height(), margin); shown.inner } +/// 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)); +} + +/// 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| { + // The windows drawn in this pass so far and in the pass before. + let (at, now, prev) = m.get_temp::<(u64, Vec, Vec)>(Id::unique(LAST_KEY)).unwrap_or_default(); + let (mut now, prev) = if at == pass { + (now, prev) + } else if at.saturating_add(1) == pass { + (vec![], now) + } else { + (vec![], vec![]) + }; + 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(|under| m.get_temp::>(under.with(HOLDS_KEY)).is_some_and(|held| held.contains(&id))) { + return false; + } + // 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) +} + /// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of /// the app would get. pub(crate) fn backdrop() -> egui::LayerId { egui::LayerId::new(egui::Order::Middle, Id::unique("modal-dim")) } +/// 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 { + 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`]). pub(crate) fn heading(ui: &mut egui::Ui, text: &str) { let t = Tokens::get(ui.ctx()); @@ -73,34 +175,159 @@ pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } -/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall -/// the rest of it was when last drawn. +/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this +/// frame, and how tall the rest of it was when last drawn. const ROWS_KEY: &str = "modal-rows"; const REST_KEY: &str = "modal-rest"; +/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to +/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`). +const OWN_ROWS_KEY: &str = "modal-own-rows"; +const OWN_BEFORE_KEY: &str = "modal-own-before"; +/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame. +const BODY_KEY: &str = "modal-body"; +/// Under a modal window's id: how large its contents would be without scrolling as a whole, this +/// frame. +const CONTENTS_KEY: &str = "modal-contents"; +/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on +/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`). +const TALL_KEY: &str = "modal-tall"; +const WHOLE_KEY: &str = "modal-whole"; +/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened, +/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so +/// they start at the top when they first do. +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`, 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"; /// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window /// would be taller than the screen. Their height is the screen's less the rest of the window as /// last drawn (a frame late, as only the drawn window knows its height). /// Rows that fit are as tall as they are. pub(crate) fn scrolled_rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - let id = ui.layer_id().id; - let rest = ui.ctx().data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); - let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0); - // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. - let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner); - ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height())); - rows.inner + fits_itself(ui); + let (r, drawn, _) = rows(ui, salt, true, add); + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn)); + r } -/// After modal window `id` is drawn `height` tall: keep the height of all of it but its -/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just -/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit -/// without waiting for input. -fn keep_rest(ctx: &egui::Context, id: Id, height: f32) { - let Some(rows) = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))) else { return }; - let rest = (height - rows).max(0.0); - let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); - if (used - rest).abs() > 0.5 { +/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing +/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window +/// scroll them again. +pub(crate) fn fits_itself(ui: &egui::Ui) { + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true)); +} + +/// The body of a shared dialog window. While the window would be taller than the screen has room +/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view; +/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is. +pub(crate) fn body_rows(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let id = ui.layer_id().id; + let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add); + if !ui.ctx().data(|m| m.get_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false) { + ui.ctx().data_mut(|m| { + m.insert_temp(id.with(ROWS_KEY), drawn); + m.insert_temp(id.with(BODY_KEY), body); + }); + } + r +} + +/// Whether the [`body_rows`] of modal window `id` scroll in this frame. +fn body_scrolls(ctx: &egui::Context, id: Id) -> bool { + let own = ctx.data(|m| m.get_temp::(id.with(OWN_BEFORE_KEY))).unwrap_or(false); + !own && ctx.data(|m| m.get_temp::(id.with(TALL_KEY))).unwrap_or(false) +} + +/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn. +pub(crate) fn body_view(ui: &egui::Ui) -> Option { + let id = ui.layer_id().id; + body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id)) +} + +/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on +/// which axes ([wide, tall]) the window scrolls as a whole. +#[cfg(test)] +pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option, [bool; 2]) { + let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id)); + (body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default()) +} + +/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`] +/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so +/// the list and its bar can be scrolled into view whole. +pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 { + body_view(ui).map_or(height, |view| view.min(height)) +} + +/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the +/// window as last drawn. +fn rows_room(ctx: &egui::Context, id: Id) -> f32 { + let rest = ctx.data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); + (ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0) +} + +/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their +/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling. +/// Rows that do not `scroll` are as tall as they are, with no +/// scroll area (which would take the scroll requests of their fields from the window's). The rows +/// keep their ids either way, so a field being edited keeps its text when they start or stop +/// scrolling. +fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) { + let id = ui.layer_id().id; + let room = rows_room(ui.ctx(), id); + let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows")); + if !scroll { + let rows = ui.scope_builder(scope, add); + let height = rows.response.rect.height(); + return (rows.inner, height, height); + } + // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. + let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room); + if ui.ctx().data_mut(|m| m.remove_temp::(id.with(TOP_ROWS_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner)); + (rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y) +} + +/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height +/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different +/// one (the window just opened, or what is around them changed), the next frame is drawn at once, +/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll +/// while the window would be taller than the screen has room for without them scrolling; a window +/// without rows that scroll scrolls as a whole while its contents would be taller than the room, +/// and any window scrolls sideways while its contents would be wider. +fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { + let rows = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))); + let body = ctx.data_mut(|m| m.remove_temp::(id.with(BODY_KEY))); + let contents = ctx.data_mut(|m| m.remove_temp::(id.with(CONTENTS_KEY))).unwrap_or_default(); + let own = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false); + ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own)); + let room = whole_room(ctx, margin); + let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP; + let tall = match (rows, body) { + (Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5, + _ => false, + }; + // A window that fits itself to the screen's height can still be too wide for it. + let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5]; + let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall)); + let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole)); + let mut repaint = tall != was_tall || whole != was_whole; + if let Some(rows) = rows { + let rest = (height - rows).max(0.0); + let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); + repaint |= (used - rest).abs() > 0.5; + } + if repaint { ctx.request_repaint(); } } @@ -146,4 +373,171 @@ mod tests { // Larger than the screen: its top left stays in view. assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0)); } + + /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal + /// windows named in `open` open, in that order: the first a heading and 60 rows, in + /// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is + /// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in + /// the last frame (inside the screen and its clip). + fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); + let add = |ui: &mut egui::Ui| { + for i in 0..60 { + ui.label(format!("Row {i}")); + } + }; + let mut events = Some(events); + let mut seen = false; + for _ in 0..frames { + *time += 1.0 / 60.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + for (i, &name) in open.iter().enumerate() { + if name.starts_with("over ") { + over_parent(ui.ctx()); + } + show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| { + heading(ui, "Top"); + if i > 0 { + ui.label("Alert"); + } else if in_rows { + scrolled_rows(ui, "rows", add); + } else { + add(ui); + } + }); + } + }); + out.textures_delta.clear(); + seen = out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r) + } + _ => false, + }); + } + seen + } + + /// A wheel turn far down, at the middle of the 400×300 screen. + fn wheel_down() -> Vec { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel] + } + + #[test] + fn a_window_that_scrolled_opens_again_at_its_top() { + for in_rows in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); + assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); + first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2); + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); + } + } + + #[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. 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 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")); + } + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + } + + #[test] + fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() { + // A field's edit state and the keyboard focus are kept under its id, so typing goes on into + // the same field when the screen's height changes whether the body or the window scrolls. + let mut wrong = vec![]; + for in_body in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let window = Id::unique("modal-field-id-test"); + let mut text = String::from("12"); + let mut time = 0.0; + let mut field = None; + let mut focus_given = false; + let mut seen = vec![]; + for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); + for i in 0..4 { + time += 1.0 / 60.0; + // Typed once the window has settled at this height. + let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] }; + let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + show(ui.ctx(), "Test", window, 0.0, 8, |ui| { + heading(ui, "Top"); + let mut add = |ui: &mut egui::Ui| { + let r = ui.text_edit_singleline(&mut text); + for i in 0..30 { + ui.label(format!("Row {i}")); + } + r.id + }; + field = Some(if in_body { body_rows(ui, add) } else { add(ui) }); + }); + }); + out.textures_delta.clear(); + // The field is given the focus once, after the first frame; a resize that took it + // away would leave the keys typed after it untaken. + if let Some(id) = field.filter(|_| !focus_given) { + ctx.memory_mut(|m| m.request_focus(id)); + focus_given = true; + } + } + let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; + let scrolls = ctx.data(|m| m.get_temp::(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1])); + seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some())); + } + let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)]; + let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect(); + if seen != want { + wrong.push((in_body, seen)); + } + } + // Only the short screen scrolls, and the field keeps its focus and takes each key. + assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong"); + } } diff --git a/crates/ui-egui/src/dialogs/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 5b6c5b117c..ec2ab707d4 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -1,5 +1,5 @@ -//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders and hex) -//! prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour +//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders, hex and the +//! colour warnings) prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour //! (saved as a tint swatch, "Name 40%") only takes a name. OK runs `swatch.new`. //! //! Fields: `name`, `spot`, `global`, `mode` and `color` as in Swatch Options, `group` (the colour @@ -45,7 +45,7 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if d.fields.contains_key("__paint") { grid(ui, |ui| name_row(ui, d)); - } else if editor(ui, d) + } else if editor(app, ui, d) && d.str("name") == d.str("__auto") && let Some(st) = app.session.active() { @@ -87,6 +87,30 @@ mod tests { assert_eq!(params(&d), json!({"name": "Dots", "pattern": "Dots"})); } + #[test] + fn a_warning_corrects_the_new_colour_only_until_ok() { + use super::super::swatch_options::tests::{click_at, context, settled, warning_rows}; + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000fe"})).unwrap(); + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatches_iter().count(); + let before = count(&app); + open(&mut app, false, false, None).unwrap(); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 2, "out of gamut and out of web colors"); + click_at(&ctx, &mut app, rows[1].1.center()); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((color_of(&d).to_hex(), d.str("mode")), ("#0000ff".to_string(), "rgb".to_string())); + assert_eq!(count(&app), before, "no swatch before OK"); + assert_eq!(warning_rows(&settled(&ctx, &mut app)).len(), 1, "the web warning is gone"); + let name = app.ui.dialog.as_ref().unwrap().str("name"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.swatch(&name).and_then(|s| s.paint.color()).map(|c| c.to_hex()), Some("#0000ff".into())); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(count(&app), before, "one undo step"); + } + #[test] fn a_tint_opens_as_a_named_tint_swatch() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 4978a6a1f6..82f0c7d78b 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -77,7 +77,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); if let Ok(attrs) = super::char_style_options::edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } }); 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/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index 4726e0762a..71aff096fb 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -11,7 +11,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::objects_on_path::CENTER; -use super::{DialogSpec, run_and_close}; +use super::{DialogSpec, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -73,7 +73,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// Save: set the tool's Pivot and Rotate. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = ["pivot", "rotate"].iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] 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/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index d63d43be89..b64815b8dd 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -952,7 +952,7 @@ pub(crate) fn general_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } @@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 3a62eae1f4..3ffc496dd6 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -198,7 +198,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { && let Some(counts) = d.fields.get("__counts") && let (Some(before), Some(after)) = (counts["before"].as_u64(), counts["after"].as_u64()) { - ui.label(format!("{}: {before} → {after}", tl!("Anchor Points"))); + ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))); } } false diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 4fc66757ac..ae70d682c4 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -63,8 +63,13 @@ pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) { false => export_size(&st.doc, ¶ms), }); if let Some(o) = params.as_object_mut() { - o.insert("ppi".into(), json!(72)); - o.extend(defaults(app, f)); + let mut initial = defaults(app, f); + initial.insert("ppi".into(), json!(72)); + for (key, value) in initial { + if o.get(&key).is_none_or(Value::is_null) { + o.insert(key, value); + } + } if let Some((w, h)) = size { o.insert("__size".into(), json!([w, h])); } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index ebaad1749a..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) } @@ -251,7 +261,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d), "Output" => output(ui, d, &preview), "Graphics" => graphics(ui, d), @@ -371,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/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index 950b15c763..c5a4c905a0 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -167,7 +167,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); - widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers"))); + widgets::dim_label(ui, &format!("{} × {} px · {} {}", count("width"), count("height"), crate::i18n::colon(tl!("Layers")), count("layers"))); // Offered only for a file with slices, with either conversion. let sliced = count("slices") > 0; ui.add_space(8.0); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index ff57bd6817..b3cb557b61 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -392,7 +392,8 @@ fn prominent_bar(ui: &mut Ui, d: &mut Dialog, rows: &[Value]) { let c = to_color(&rows[*i]).or_else(|| from_colors(&rows[*i]).first().copied()).unwrap_or_default(); chip(ui, r, c, false); let share = (widths[n] * 100.0).round(); - ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()).on_hover_text(format!("{} {}: {share}%", tl!("Color"), i + 1)); + ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()) + .on_hover_text(format!("{} {share}%", crate::i18n::colon(&format!("{} {}", tl!("Color"), i + 1)))); left = right; } let mut ended = false; @@ -1949,7 +1950,7 @@ fn global_sliders(ui: &mut Ui, d: &mut Dialog, sample: Color) { /// and its number field, showing `shown` with `suffix`. Returns the whole number in `shown`'s /// range that a drag, a key or the field sets. #[allow(clippy::too_many_arguments)] -fn slider_cell( +pub(crate) fn slider_cell( ui: &mut Ui, id: impl std::hash::Hash + Copy, label: &str, @@ -3599,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() { @@ -3622,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/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 77c5980ec0..c7c98a5de0 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -733,7 +733,7 @@ pub(super) fn reset_dot(ui: &mut egui::Ui, key: &str, changed: bool, default: &s ui.painter().rect_filled(r, 3.0, Tokens::get(ui.ctx()).hover); } dot(ui, r.center(), changed); - response.on_hover_text(format!("{}: {default}", tl!("Reset to default"))).clicked() + response.on_hover_text(format!("{} {default}", crate::i18n::colon(tl!("Reset to default")))).clicked() } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 3d522b624a..dadab71c70 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -75,7 +75,8 @@ impl Light { /// The name screen readers give the light at `index`: its number, Rotation, Height and side. fn name(self, index: usize) -> String { let side = if self.behind { format!(", {}", tl!("Light behind the object")) } else { String::new() }; - format!("{} {}: {} {:.1}°, {} {:.1}°{side}", c3("Light"), index + 1, tl!("Rotation"), self.rotation, tl!("Height"), self.height) + let light = crate::i18n::colon(&format!("{} {}", c3("Light"), index + 1)); + format!("{light} {} {:.1}°, {} {:.1}°{side}", tl!("Rotation"), self.rotation, tl!("Height"), self.height) } } diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 589d1dfdce..7ad629afb8 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -2,13 +2,18 @@ //! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views, //! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8, //! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap, -//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort), image size -//! and anti-aliasing, Clip to Artboard, sRGB, metadata, slices and HTML output, and presets. +//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color, +//! Restore Generated Table, a double-click that shifts a color to one picked in the Color Picker, +//! and Unshift All Colors), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, +//! slices and HTML output, and presets. //! //! Fields are the `document.exportForWeb` settings (`webExport.settings` gives them; set one with //! `ui.dialog.set`, or `preset` to load a preset), plus the dialog's own: `__view` (`original`, //! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed), -//! `__color` (the colour table's selected colour, by source), `__presetName` (shown while saving a +//! `__color` (the colour table's selected colour, by source: the one Lock, Transparent and Web +//! Shift edit, and where a Shift-click range starts), `__colors` (every selected color, by source, +//! which Delete Color deletes; when it is empty, `__color` alone), `__editColor` (a source color: +//! the Color Picker opens on it, as a double-click on its swatch opens it), `__presetName` (shown while saving a //! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K), //! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`, //! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and @@ -52,6 +57,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// The preview area (panes and their captions) and the settings column. const PREVIEW_W: f32 = 620.0; +/// The narrowest the panes get in a narrow window. +const MIN_PREVIEW_W: f32 = 240.0; const PREVIEW_H: f32 = 470.0; const SIDE_W: f32 = 296.0; const GAP: f32 = 16.0; @@ -107,10 +114,10 @@ fn remembered(app: &VectorcraftApp) -> WebSettings { /// Reset (Cancel with Alt or Option held, or `ui.dialogReset`): the settings go back to the /// remembered ones on the document's active artboard ([`remembered`]), and a pending `preset`, a /// pending Done (`discard`, which a failed Done leaves), the preset name being typed and the -/// selected color table entry are dropped. The view, zoom, connection speed and `path` stay, +/// selected color table entries are dropped. The view, zoom, connection speed and `path` stay, /// nothing is remembered or written, and the dialog stays open. fn reset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { - for key in ["preset", "discard", "__presetName", "__color"] { + for key in ["preset", "discard", "__presetName", "__color", "__colors"] { d.fields.remove(key); } d.fields.extend(settings_fields(&remembered(app))); @@ -237,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) }) } @@ -381,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()) } @@ -530,12 +549,22 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { { app.status(e); } + take_shift(d); let settings = settings_of(app, d); let mut browser = false; - ui.horizontal_top(|ui| { + // In a window too narrow for both, the panes are narrower, so the settings beside them and the + // buttons below stay in view. The room is the screen's (the window's own width follows what it + // drew last), less a column for the bar of the body while it scrolls; the settings column is as + // wide as it was drawn last. + let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 }; + let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar; + let rest_id = egui::Id::unique("save-for-web-beside-panes"); + let rest = ui.ctx().data(|m| m.get_temp::(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W); + let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W); + let row = ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(PREVIEW_W); - browser = preview_area(app, ui, d, &settings); + ui.set_width(preview_w); + browser = preview_area(app, ui, d, &settings, preview_w); }); ui.add_space(GAP); ui.vertical(|ui| { @@ -543,23 +572,33 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { side(app, ui, d, settings.as_ref().ok()); }); }); + let drawn = row.response.rect.width() - preview_w; + if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 { + ui.ctx().request_repaint(); + } optimize_on_enter(ui.ctx(), d); if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) { app.status(e); } + // A double-clicked swatch (or an agent's `__editColor`) opens the Color Picker last, over the + // dialog as it now is. + if let Some(source) = d.fields.remove("__editColor").and_then(|v| v.as_str().map(String::from)) { + let start = d.fields.remove("__editStart").and_then(|v| v.as_str().map(String::from)).unwrap_or_else(|| source.clone()); + edit_color(d, &source, &start); + } false } -/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was -/// clicked. -fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result) -> bool { +/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in +/// Browser was clicked. +fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result, width: f32) -> bool { let t = Tokens::get(ui.ctx()); let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2); if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) { d.fields.insert("__view".into(), json!(VIEWS[i])); } ui.add_space(4.0); - let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag()); + let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag()); let pan_id = egui::Id::unique("save-for-web-pan"); let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default(); if resp.dragged() { @@ -604,6 +643,17 @@ 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. + 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| { + let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, label)); + browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); + }); + }; ui.horizontal(|ui| { let z = ZOOMS.iter().position(|z| *z == d.str("__zoom")).unwrap_or(2); let zoom = ui.name_inputs(tl!("Zoom"), |ui| widgets::dropdown(ui, "sfw-zoom", ZOOM_LABELS[z], &ZOOM_LABELS, 110.0)); @@ -620,11 +670,15 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set { d.fields.insert("__kbps".into(), json!(s)); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Preview in Browser"))); - browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); - }); + beside = ui.available_width() >= button_w; + if beside { + button(ui); + } }); + if !beside { + ui.add_space(4.0); + ui.horizontal(button); + } browser } @@ -729,7 +783,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& presets_row(app, ui, d, s); optimize_rows(ui, d, s, &art_key(app)); widgets::divider(ui); - egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| { + let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0); + egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| { form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options); }; @@ -737,7 +792,12 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& let format = s.map_or(WebFormat::Gif, |s| s.format); match format { WebFormat::Gif | WebFormat::Png8 => { + let reduction = d.str("reduction"); choice(ui, d, "reduction", tl!("Reduction:"), &pairs(&Reduction::ALL, Reduction::id, Reduction::label)); + // Another reduction makes a new palette. + if d.str("reduction") != reduction { + restore_table(d); + } colors_row(ui, d); choice(ui, d, "dither", tl!("Dither:"), &pairs(&Dither::ALL, Dither::id, Dither::label)); if Dither::from_id(&d.str("dither")).is_some_and(|x| x != Dither::None) { @@ -765,7 +825,9 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& choice(ui, d, "metadata", tl!("Metadata:"), &pairs(&WebMetadata::ALL, WebMetadata::key, WebMetadata::label)); if format.palette() { widgets::divider(ui); - color_table(ui, d, s); + if let Err(e) = color_table(ui, d, s) { + app.status(e); + } } widgets::divider(ui); image_size(app, ui, d, s); @@ -1043,10 +1105,15 @@ fn matte_row(ui: &mut egui::Ui, d: &mut Dialog) { }); } -/// The colour table of the current settings' preview: swatches (the selected one ringed; locked -/// ones with a square, web-safe ones with a diamond, transparent ones over the grid) and the -/// buttons that edit the selected colour, plus the sort order. -fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { +/// The colour table of the current settings' preview: swatches (the selected ones ringed; locked +/// ones with a square, web-safe ones with a diamond, transparent ones over the grid), the buttons +/// that edit the selected colour, Delete Color and the table's menu, plus the sort order. A click +/// selects one color, a Shift-click the colors from the anchor, and a Ctrl-click +/// (Command-click on macOS) adds or removes one; a double-click on an opaque color asks for the +/// Color Picker (`__editColor`), and a color shifted by hand shows its source color at the upper +/// left and its new color at the lower right. Returns an error for a deletion that would leave +/// no color. +fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Result<(), String> { let t = Tokens::get(ui.ctx()); let cache: Option = ui.ctx().data(|m| m.get_temp(cache_id())); let key = s.map(|s| s.to_json().to_string()); @@ -1054,21 +1121,39 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { let Some(shot) = shot else { widgets::subheader(ui, tl!("Color Table")); widgets::dim_label(ui, tl!("Shown with the optimised preview.")); - return; + // A Custom table the preview can't use (a deletion that left only colors mapped to + // transparent) can still go back to the generated palette. + if s.is_some_and(|s| s.color_table.is_custom()) && widgets::flat_button_fit(ui, tl!("Restore Generated Table"), 88.0).clicked() { + restore_table(d); + } + return Ok(()); }; + let table = s.map(|s| s.color_table.clone()).unwrap_or_default(); widgets::subheader(ui, &crate::i18n::tn(shot.colors.len() as u64, "Color Table ({n} color)", "Color Table ({n} colors)")); + if table.is_custom() { + widgets::dim_label(ui, tl!("Custom")); + } let selected = d.str("__color"); + let picked = selection(d); // (colour shown, source, transparent, locked, web-safe, mapped by hand) let rows: Vec<(TableColor, bool)> = shot .colors .iter() .map(|c| (*c, false)) - .chain(shot.mapped.iter().map(|c| (TableColor { color: *c, source: *c, transparent: true, locked: false, web_shifted: false }, true))) + .chain( + shot.mapped + .iter() + .map(|c| (TableColor { color: *c, source: *c, transparent: true, locked: false, web_shifted: false, shifted: false }, true)), + ) .collect(); const CELL: f32 = 15.0; let per_row = ((SIDE_W - 8.0) / (CELL + 2.0)).floor().max(1.0) as usize; let lines = rows.len().div_ceil(per_row).max(1); - let (area, resp) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::click()); + let (area, _) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::hover()); + // The colors that can be selected, in table order (for Shift-click ranges). + let order: Vec = rows.iter().filter(|(c, mapped)| !c.transparent || *mapped).map(|(c, _)| hex(c.source)).collect(); + let mut clicked = None; + let mut edit = None; let p = ui.painter(); for (i, (c, mapped)) in rows.iter().enumerate() { let r = egui::Rect::from_min_size( @@ -1087,6 +1172,15 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { } } else { p.rect_filled(r, 0.0, fill); + if c.shifted { + // Shifted by hand: the source color at the upper left, the new one at the lower right. + let [red, g, b] = c.source; + p.add(egui::Shape::convex_polygon( + vec![r.left_top(), r.right_top(), r.left_bottom()], + egui::Color32::from_rgb(red, g, b), + egui::Stroke::NONE, + )); + } } let mark = if c.color.iter().map(|v| u32::from(*v)).sum::() > 380 { egui::Color32::BLACK } else { egui::Color32::WHITE }; if c.locked { @@ -1102,17 +1196,39 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { } // The transparent entry itself isn't a colour to edit. let pickable = !c.transparent || *mapped; - let picked = pickable && hex(c.source) == selected; - p.rect_stroke(r, 0.0, egui::Stroke::new(if picked { 2.0 } else { 1.0 }, if picked { t.accent } else { t.border }), egui::StrokeKind::Outside); - if pickable && resp.clicked() && resp.interact_pointer_pos().is_some_and(|pos| r.contains(pos)) { - d.fields.insert("__color".into(), json!(hex(c.source))); + let ringed = pickable && picked.iter().any(|h| h.eq_ignore_ascii_case(&hex(c.source))); + p.rect_stroke(r, 0.0, egui::Stroke::new(if ringed { 2.0 } else { 1.0 }, if ringed { t.accent } else { t.border }), egui::StrokeKind::Outside); + if !pickable { + continue; + } + let resp = ui.interact(r, swatch_id(&hex(c.source)), egui::Sense::click()); + if resp.clicked() { + clicked = Some(hex(c.source)); + } + // A double-click edits an opaque color: the picker opens on the color as shown, or on the + // source color for a color already shifted by hand. + if resp.double_clicked() && !c.transparent { + edit = Some((hex(c.source), hex(if c.shifted { c.source } else { c.color }))); } } + if let Some(c) = clicked { + let m = ui.input(|i| i.modifiers); + pick(d, &order, &c, m.shift, m.command); + } + if let Some((source, start)) = edit { + d.fields.insert("__editColor".into(), json!(source)); + d.fields.insert("__editStart".into(), json!(start)); + } + let shifted = |c: &str| table.shifted.keys().any(|k| k.eq_ignore_ascii_case(c)); + // The colors the table shows, by source: Lock, Transparent, Web Shift and Delete Color act only + // on these. + let palette: Vec = + shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect(); + let shown = palette.iter().any(|p| p.eq_ignore_ascii_case(&selected)); ui.add_space(4.0); - let table = s.map(|s| s.color_table.clone()).unwrap_or_default(); let on = |list: &[String]| list.iter().any(|h| h.eq_ignore_ascii_case(&selected)); ui.horizontal(|ui| { - ui.add_enabled_ui(!selected.is_empty(), |ui| { + ui.add_enabled_ui(shown, |ui| { for (list, on_label, off_label) in [ ("transparent", tl!("Restore"), tl!("Transparent")), ("webShift", tl!("Unshift"), tl!("Web Shift")), @@ -1123,13 +1239,43 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { "webShift" => &table.web_shift, _ => &table.locked, }; - let is_on = on(current); - if widgets::flat_button(ui, if is_on { on_label } else { off_label }, 88.0).clicked() { + // A color shifted by hand stays locked until it is unshifted. + let fixed = list == "locked" && shifted(&selected); + let is_on = on(current) || fixed; + let label = if is_on { on_label } else { off_label }; + if ui.add_enabled(!fixed, |ui: &mut egui::Ui| widgets::flat_button(ui, label, 88.0)).clicked() { toggle(d, list, &selected, !is_on); + // Web Shift replaces a shift by hand. + if list == "webShift" && !is_on { + unshift(d, &selected); + } } } }); }); + // Delete Color (the button and the table's menu) and Restore Generated Table. Delete Color + // takes only selected colors the table shows (`palette`, by source). + let deletable = !selected_in(d, &palette).is_empty(); + let (mut delete, mut restore, mut unshift_all) = (false, false, false); + ui.horizontal(|ui| { + delete |= widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Color"), false, deletable, 24.0).clicked(); + let menu = widgets::icon_button(ui, "menu", tl!("Color Table"), false, 24.0); + let open = menu.clicked(); + let _ = widgets::popover(&menu, open, |ui| { + if widgets::menu_item(ui, tl!("Delete Color"), deletable, false) { + delete = true; + ui.close(); + } + if widgets::menu_item(ui, tl!("Restore Generated Table"), table.is_custom(), false) { + restore = true; + ui.close(); + } + if widgets::menu_item(ui, tl!("Unshift All Colors"), !table.shifted.is_empty() || !table.web_shift.is_empty(), false) { + unshift_all = true; + ui.close(); + } + }); + }); let sort = table.sort; widgets::label_row(ui, tl!("Order:"), LABEL_W, |ui| { let labels = ColorSort::ALL.map(ColorSort::label); @@ -1139,6 +1285,195 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { set_table(d, "sort", json!(o.id())); } }); + if restore { + restore_table(d); + } + if unshift_all { + unshift_all_colors(d); + } + if delete { + delete_colors(d, &palette)?; + } + Ok(()) +} + +/// The selected colors (by source) that `palette`, the colors the table shows, holds. +pub(super) fn selected_in(d: &Dialog, palette: &[String]) -> Vec { + selection(d).into_iter().filter(|c| palette.iter().any(|p| p.eq_ignore_ascii_case(c))).collect() +} + +/// The colour table's selected colors, by source: `__colors`, else `__color`. +pub(super) fn selection(d: &Dialog) -> Vec { + let many: Vec = + d.fields.get("__colors").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_ascii_lowercase).collect(); + if !many.is_empty() { + return many; + } + let one = d.str("__color"); + if one.is_empty() { vec![] } else { vec![one.to_ascii_lowercase()] } +} + +/// A click on the table's color `color`: it alone is selected and becomes the anchor (`__color`); +/// with `shift`, the colors from the anchor to it in table order (`order`), the anchor unchanged; +/// with `command` (Ctrl, or Command on macOS), it is added to the selection and becomes the anchor, +/// or taken out, and the anchor moves to the last color left in the selection. +pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, command: bool) { + let color = color.to_ascii_lowercase(); + let at = |c: &str| order.iter().position(|o| o.eq_ignore_ascii_case(c)); + if shift && let (Some(a), Some(b)) = (at(&d.str("__color")), at(&color)) { + let range: Vec = order[a.min(b)..=a.max(b)].iter().map(|c| c.to_ascii_lowercase()).collect(); + d.fields.insert("__colors".into(), json!(range)); + return; + } + let mut set = selection(d); + let anchor = if command { + match set.iter().position(|c| *c == color) { + Some(i) => { + set.remove(i); + set.last().cloned() + } + None => { + set.push(color.clone()); + Some(color) + } + } + } else { + set = vec![color.clone()]; + Some(color) + }; + d.fields.insert("__colors".into(), json!(set)); + match anchor { + Some(c) => d.fields.insert("__color".into(), json!(c)), + None => d.fields.remove("__color"), + }; +} + +/// Delete Color: the selected colors join the color table's `deleted` list and leave its other +/// lists. The first deletion fixes the palette (`customPalette`) to `palette`, the table's colors +/// (by source) with the deleted ones, so the colors left do not change. A deletion that leaves no +/// color, or only colors mapped to transparent, is refused with nothing changed. Only selected +/// colors that `palette` holds are deleted; when it holds none of them, the table is left as it is +/// and the selection is cleared. The selection is cleared after a deletion too. +pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), String> { + let picked = selected_in(d, palette); + if picked.is_empty() { + d.fields.remove("__colors"); + d.fields.remove("__color"); + return Ok(()); + } + let list = |d: &Dialog, key: &str| -> Vec { + d.fields + .get("colorTable") + .and_then(|t| t.get(key)) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_ascii_lowercase) + .collect() + }; + let mut custom = list(d, "customPalette"); + if custom.is_empty() { + custom = palette.iter().map(|c| c.to_ascii_lowercase()).collect(); + } + let mut deleted = list(d, "deleted"); + for c in &picked { + if !deleted.contains(c) { + deleted.push(c.clone()); + } + } + // A color has to stay that is neither deleted nor mapped to transparent. + let clear: Vec = list(d, "transparent").into_iter().filter(|c| !picked.contains(c)).collect(); + if custom.iter().all(|c| deleted.contains(c) || clear.contains(c)) { + return Err(webexport::KEEP_ONE.into()); + } + for key in ["locked", "transparent", "webShift"] { + if list(d, key).iter().any(|c| picked.contains(c)) { + for c in &picked { + toggle(d, key, c, false); + } + } + } + for c in &picked { + unshift(d, c); + } + set_table(d, "customPalette", json!(custom)); + set_table(d, "deleted", json!(deleted)); + d.fields.remove("__colors"); + d.fields.remove("__color"); + Ok(()) +} + +/// Restore Generated Table: no deleted colors and no fixed palette; the reduction makes the +/// palette again. +pub(super) fn restore_table(d: &mut Dialog) { + set_table(d, "deleted", json!([])); + set_table(d, "customPalette", json!([])); +} + +/// The id of the color table's swatch for the source color `source` (`#rrggbb`). +pub(super) fn swatch_id(source: &str) -> egui::Id { + egui::Id::unique(("sfw-swatch", source.to_ascii_lowercase())) +} + +/// The field of the Color Picker's OK over Save for Web: the color the edited swatch shifts to. +const SHIFT_TO: &str = "__shiftTo"; + +/// The Color Picker over the dialog for the color table's source color `source`, on `start`; its +/// OK shifts the color ([`shift_color`]) and its Cancel leaves the table as it was. Nothing opens +/// when either is not a color. +pub(super) fn edit_color(d: &mut Dialog, source: &str, start: &str) { + let (Some(_), Some(c)) = (vectorcraft_color::Color::from_hex(source), vectorcraft_color::Color::from_hex(start)) else { return }; + d.fields.insert("__shiftSource".into(), json!(source)); + *d = super::color_picker::over_effect(d, SHIFT_TO, c); +} + +/// Back from the Color Picker: its OK's color shifts the color it was opened for. +fn take_shift(d: &mut Dialog) { + let source = d.fields.remove("__shiftSource"); + if let (Some(to), Some(source)) = (d.fields.remove(SHIFT_TO), source) + && let (Some(to), Some(source)) = (to.as_str(), source.as_str()) + { + shift_color(d, source, to); + } +} + +/// Shift the source color `source` to `to` (`colorTable.shifted`), wherever it is in the image; it +/// is no longer web-shifted. Picking the source color itself takes the shift away. The color +/// becomes the selection. Nothing changes when either is not a color. +pub(super) fn shift_color(d: &mut Dialog, source: &str, to: &str) { + let hex = |h: &str| vectorcraft_color::Color::from_hex(h).map(|c| c.to_hex()); + let (Some(source), Some(to)) = (hex(source), hex(to)) else { return }; + unshift(d, &source); + if to != source { + let mut map = shifts(d); + map.insert(source.clone(), json!(to)); + set_table(d, "shifted", Value::Object(map)); + } + toggle(d, "webShift", &source, false); + d.fields.insert("__colors".into(), json!([source])); + d.fields.insert("__color".into(), json!(source)); +} + +/// The `colorTable.shifted` field. +fn shifts(d: &Dialog) -> Map { + d.fields.get("colorTable").and_then(|t| t.get("shifted")).and_then(Value::as_object).cloned().unwrap_or_default() +} + +/// Take the shift by hand of the source color `source` away. +pub(super) fn unshift(d: &mut Dialog, source: &str) { + let mut map = shifts(d); + let before = map.len(); + map.retain(|k, _| !k.eq_ignore_ascii_case(source)); + if map.len() != before { + set_table(d, "shifted", Value::Object(map)); + } +} + +/// Unshift All Colors: no color is shifted by hand or web-shifted. +pub(super) fn unshift_all_colors(d: &mut Dialog) { + set_table(d, "shifted", json!({})); + set_table(d, "webShift", json!([])); } /// Add `color` to the colour table's `list`, or take it out. diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 111d400a3b..85ff601db0 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -152,10 +152,31 @@ fn params(d: &Dialog) -> Value { p } -/// Save PDF: write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); -/// the dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for -/// a name, OK (and Enter) saves the preset instead. +/// The field that holds why the last Save PDF failed, shown in the dialog (the status bar sits +/// behind it, #6861). +const ERROR: &str = "__error"; + +/// Save PDF: write the file (see [`write`]). When that fails the dialog stays open and says why, +/// under its sections, as well as in the status bar the dialog covers. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let r = write(app, d); + if let Some(open) = app.ui.dialog.as_mut().filter(|o| o.kind == d.kind) { + match &r { + Err(e) => { + open.fields.insert(ERROR.into(), json!(e)); + } + Ok(_) => { + open.fields.remove(ERROR); + } + } + } + r +} + +/// Write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); the +/// dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for a +/// name, OK (and Enter) saves the preset instead. +fn write(app: &mut VectorcraftApp, d: &Dialog) -> Result { if d.fields.contains_key(SAVE_AS) { let mut d = d.clone(); let r = save_preset(app, &mut d); @@ -408,7 +429,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Compression" => compression(ui, d), "Marks and Bleeds" => marks_and_bleeds(app, ui, d), "Output" => output(ui, d), @@ -417,6 +439,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { "Summary" => summary(app, ui, d), _ => general(ui, d, editor), }); + if let Some(e) = d.fields.get(ERROR).and_then(Value::as_str) { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), e)).color(t.error)); + } }); }); false @@ -452,7 +478,8 @@ pub(super) fn section_list(ui: &mut egui::Ui, d: &mut Dialog, sections: &[&str], /// What choosing `standard` changes: the compatibility, to its version unless it allows the one /// chosen, and off what files of a standard can't have (editing data, passwords; layers in PDF/X-1a -/// and PDF/X-3). +/// and PDF/X-3). In PDF/X-3 and PDF/X-4, Profile inclusion goes back to unset: the picker is +/// disabled there, and `none` would write every CMYK color as DeviceCMYK. fn standard_chosen(d: &mut Dialog, standard: Standard) { if choice::(d, "compatibility").is_some_and(|c| !standard.allows(c)) { set(d, "compatibility", json!(standard.version().id())); @@ -466,6 +493,9 @@ fn standard_chosen(d: &mut Dialog, standard: Standard) { if !standard.allows_layers() { set(d, "createLayers", json!(false)); } + if standard.is_pdfx() && !standard.cmyk_only() { + set(d, "output.profiles", json!(vectorcraft_pdf::UNSET_CHOICE)); + } } /// The Preset row (the presets, built-in and saved, and Save Preset…) and, while Save Preset… @@ -522,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); } @@ -657,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. @@ -712,6 +825,22 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { }); if standard.cmyk_only() { note(ui, tl!("PDF/X-1a files are CMYK: every colour is converted to the destination (blank: the output intent's CMYK profile), untagged.")); + } else if standard.is_pdfx() { + note( + ui, + tl!( + "Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK." + ), + ); + // A preset or the dialog's params can bring `none` with the standard; the picker can't change it. + if choice::(d, "output.profiles") == Some(ProfileInclusion::None) { + note( + ui, + tl!( + "With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile." + ), + ); + } } else if standard != Standard::None { note(ui, tl!("Files of this standard tag their colours with ICC profiles.")); } @@ -912,7 +1041,7 @@ pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator s.clone(), other => other.to_string(), }; - ui.label(egui::RichText::new(format!("{}: {value}", label(c["option"].as_str().unwrap_or_default()))).color(t.text)); + ui.label(egui::RichText::new(format!("{} {value}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())))).color(t.text)); } } diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 91442f111c..1f04c8c912 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -92,6 +92,27 @@ fn confirm_runs_export_pdf_with_the_dialog_options() { assert!(app.ui.status.starts_with("Saved /tmp/out.pdf"), "{}", app.ui.status); } +/// A Save PDF that fails keeps the dialog open and says why inside it (#6861): the status bar is +/// behind the dialog. Saving again, once it works, clears the message. +#[test] +fn a_failed_save_says_why_in_the_dialog() { + let (mut app, written, _) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf"})).unwrap(); + set_field(&mut app, "__allArtboards", json!(false)); + set_field(&mut app, "range", json!("9")); + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(written.borrow().is_empty(), "nothing was written"); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.str(ERROR), e, "the dialog holds the reason"); + assert!(!e.is_empty()); + assert!(params(d).get(ERROR).is_none(), "the message is not an option of the export"); + frame(&mut app); + set_field(&mut app, "range", json!("1")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(written.borrow().len(), 1); +} + /// Opened for a page of the art's bounds (Export As with Use Artboards off), the dialog has no /// Artboards section, and OK writes one page of the art's bounds with its options, a saved preset /// and View PDF after Saving included. @@ -443,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"); @@ -537,6 +753,39 @@ fn choosing_a_pdfx_standard_sets_its_version_and_writes_the_standard() { assert_eq!((get(d, "compatibility"), get(d, "createLayers")), (&json!("1.6"), &json!(true))); } +/// Profile inclusion is disabled with a standard, so choosing PDF/X-3 or PDF/X-4 sets it back to +/// unset: a `none` chosen before would write every CMYK color as DeviceCMYK. +#[test] +fn choosing_pdfx3_or_pdfx4_unsets_profile_inclusion() { + let (mut app, _, _) = app(); + for standard in [Standard::PdfX3, Standard::PdfX4] { + app.run("ui.savePdfDialog", json!({"path": "/tmp/x.pdf", "output": {"profiles": "none"}})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(get(d, "output.profiles"), &json!("none")); + set(d, "standard", json!(standard.id())); + standard_chosen(d, standard); + assert_eq!(get(d, "output.profiles"), &json!(vectorcraft_pdf::UNSET_CHOICE), "{}", standard.id()); + } +} + +/// Opened with PDF/X-3 or PDF/X-4 and `none` (params or a preset, without choosing the standard), +/// the dialog keeps `none` and its Output note says every CMYK color is written as DeviceCMYK. +#[test] +fn a_loaded_pdfx_standard_with_no_profiles_says_cmyk_is_device_cmyk() { + const NOTE: &str = "every CMYK color is written as DeviceCMYK"; + let (mut app, _, _) = app(); + for (standard, profiles, shown) in + [(Standard::PdfX4, "none", true), (Standard::PdfX3, "none", true), (Standard::PdfX4, "all", false), (Standard::PdfX1a, "none", false)] + { + let params = json!({"path": "/tmp/x.pdf", "standard": standard.id(), "output": {"profiles": profiles}}); + app.run("ui.savePdfDialog", params).unwrap(); + set_field(&mut app, "__section", json!("Output")); + assert_eq!(get(app.ui.dialog.as_ref().unwrap(), "output.profiles"), &json!(profiles)); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert_eq!(text.contains(NOTE), shown, "{} {profiles}: {text}", standard.id()); + } +} + /// "Write pages longer than 200 in at full size in points" is enabled only without a standard, at /// PDF 1.5 and later: PDF/X files and PDF 1.3 and 1.4 files write long pages in points anyway, and /// PDF/A files keep the `UserUnit`. diff --git a/crates/ui-egui/src/dialogs/script_check.rs b/crates/ui-egui/src/dialogs/script_check.rs index 257227cc6f..e134cf1b39 100644 --- a/crates/ui-egui/src/dialogs/script_check.rs +++ b/crates/ui-egui/src/dialogs/script_check.rs @@ -271,7 +271,7 @@ fn report(ui: &mut egui::Ui, r: &Value, t: &Tokens) { for p in problems { let Some(label) = p["code"].as_str().and_then(problem_label) else { continue }; let label = match p["detail"].as_str() { - Some(detail) => format!("{label}: {detail}"), + Some(detail) => format!("{} {detail}", crate::i18n::colon(label)), None => label.to_string(), }; row(ui, t, &label, false, &place(p)); diff --git a/crates/ui-egui/src/dialogs/shape_builder_options.rs b/crates/ui-egui/src/dialogs/shape_builder_options.rs index 9393e0707e..d4edbad1f9 100644 --- a/crates/ui-egui/src/dialogs/shape_builder_options.rs +++ b/crates/ui-egui/src/dialogs/shape_builder_options.rs @@ -14,7 +14,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -124,7 +124,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("highlightColor"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": "shapeBuilder", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "shapeBuilder", "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 3040097a25..c77b9a080e 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -102,8 +102,8 @@ fn line_length_angle(d: &Dialog) -> (f64, f64) { fn arc_options(d: &Dialog) -> Value { json!({ "closed": d.str("arcType").eq_ignore_ascii_case("closed"), - "lengthX": d.f64("lengthX", 100.0), - "lengthY": d.f64("lengthY", 100.0), + "lengthX": d.f64("lengthX", 100.0).abs(), + "lengthY": d.f64("lengthY", 100.0).abs(), "reference": arc_reference(d), "baseAlong": d.str("baseAlong"), "slope": d.f64("slope", 50.0), @@ -270,8 +270,8 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { const ARC_PREVIEW: egui::Vec2 = egui::vec2(160.0, 120.0); const ARC_PREVIEW_MARGIN: f32 = 12.0; -/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`], kept as the tool -/// keeps them: a slope from -100 to 100, a Base Along of Y or else X), as `shape.arc` draws it +/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`]; a slope past -100 +/// or 100, which OK refuses, is drawn at that end, and a Base Along other than Y along X), as `shape.arc` draws it /// with its reference point at the origin and General › Constrain Angle `constrain` (degrees) /// turning it about that point. `None` when a length or the slope is not finite. fn arc_preview_path(d: &Dialog, constrain: f64) -> Option { @@ -554,13 +554,11 @@ fn box_origin(d: &Dialog) -> (f64, f64) { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // Tool Options: the options the tool's next drag and click use; nothing is drawn. if d.bool(TOOL_OPTIONS) { - let r = app.run("tool.setOption", json!({"tool": d.kind, "values": tool_options(d)})); - app.ui.dialog = None; - return r; + return super::set_tool_options_and_close(app, json!({"tool": d.kind, "values": tool_options(d)})); } let count = match d.kind.as_str() { "polygon" => Some(("sides", 6.0, 3.0)), - "star" => Some(("points", 5.0, 2.0)), + "star" => Some(("points", 5.0, 3.0)), _ => None, }; let options = count @@ -590,7 +588,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { "cx": x, "cy": y, "radius": d.f64("radius", 50.0).max(0.01), - "decay": d.f64("decay", 80.0).clamp(5.0, 150.0), + "decay": d.f64("decay", 80.0).clamp(5.0, 99.99), "segments": (d.f64("segments", 10.0) as u64).clamp(2, 1000), "clockwise": d.bool("clockwise"), }), @@ -648,7 +646,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // On the active plane while the perspective grid shows, sized in plane units from the click; // else along General › Constrain Angle, turned about the point the dialog places at the click // (a grid's reference point, the other shapes' top-left corner or centre). - let options = options.or_else(|| (d.kind == "spiral").then(|| params.clone())); + let options = options.or_else(|| { + (d.kind == "spiral").then(|| json!({"decay": params["decay"], "segments": params["segments"], "clockwise": params["clockwise"]})) + }); + // Options the tool would refuse leave the dialog open, before anything is drawn. + if let Some(Value::Object(o)) = &options { + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create(&d.kind).as_ref(), o)?; + } let result = match vectorcraft_engine::perspective_click(&app.session, id, ¶ms, vectorcraft_geom::Point::new(x, y)) { Some((id, params)) => run_and_close(app, &id, params), None => { @@ -707,6 +711,15 @@ mod tests { assert!(app.ui.dialog.is_none()); assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true})); + + // A decay typed past 99.99 % draws the spiral at 99.99 %, the most a spiral draws, and + // keeps that decay. + super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("decay".into(), json!(120.0)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + assert_eq!(app.session.tool_options_of("spiral")["decay"], json!(99.99)); } /// With General › Constrain Angle at 90°, the Spiral dialog's spiral starts straight up from the @@ -812,21 +825,27 @@ mod tests { } } - /// For values the Arc tool does not keep as typed, the picture shows the arc of the options OK - /// sets: the same picture as a dialog holding those options. + /// For values the dialog reads as other values, the picture shows the arc of the options OK + /// sets: the same picture as a dialog holding those options. A slope outside -100 to 100 or a + /// Base Along other than X or Y is refused: OK leaves the dialog open and keeps the options. #[test] fn the_arc_preview_shows_the_options_ok_sets() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); - for typed in [ - json!({"slope": 140.0}), - json!({"slope": -250.0}), - json!({"slope": "steep"}), - json!({"lengthX": "wide"}), - json!({"lengthY": null}), - json!({"baseAlong": "z"}), - json!({"reference": 12}), + for (typed, error) in [ + (json!({"slope": 140.0}), "`slope` must be a number from -100 to 100"), + (json!({"slope": -250.0}), "`slope` must be a number from -100 to 100"), + (json!({"baseAlong": "z"}), "`baseAlong` must be one of"), ] { + let before = app.session.tool_options_of("arc"); + app.ui.dialog = Some(arc_dialog(typed.clone())); + let r = super::super::confirm(&mut app); + assert!(r.as_ref().is_err_and(|e| e.contains(error)), "{typed}: {r:?}"); + assert!(app.ui.dialog.is_some(), "{typed}"); + assert_eq!(app.session.tool_options_of("arc"), before, "{typed}"); + app.ui.dialog = None; + } + for typed in [json!({"slope": "steep"}), json!({"lengthX": "wide"}), json!({"lengthY": null}), json!({"reference": 12})] { let d = arc_dialog(typed.clone()); let shown = arc_preview_path(&d, 0.0).expect("an arc"); app.ui.dialog = Some(d); @@ -1112,9 +1131,11 @@ mod tests { super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0); app.ui.dialog = None; - // `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps. - for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] { - app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap(); + // `tool.setOption` takes it from 2 to 1000 and refuses other counts, and the dialog opens on + // what it keeps. + for (set, want) in [(json!(1), 6.0), (json!(2000), 6.0), (json!(2), 2.0), (json!(1000), 1000.0), (json!(7), 7.0)] { + let r = app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})); + assert_eq!(r.is_ok(), set.as_u64().is_some_and(|n| (2..=1000).contains(&n)), "{set}: {r:?}"); super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}"); app.ui.dialog = None; diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index 0516695233..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."))); } @@ -670,6 +674,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open); let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0); crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| { + crate::dialogs::modal::fits_itself(ui); ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0); crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set")); ui.add_space(10.0); diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 1ebe084e02..ce6f62c6a2 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -98,7 +98,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let lines: Vec = options() .into_iter() .filter(|(key, ..)| d.bool(key)) - .map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0))) + .map(|(_, count, label)| format!("{} {}", crate::i18n::colon(label), r["replaced"][count].as_u64().unwrap_or(0))) .collect(); super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n")); } 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("