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 4358817b60..ea37f12caf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -128,16 +128,20 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged. - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. +- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged. - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. +- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged. - 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. @@ -150,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-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index e597db66f1..d1ead11969 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,12 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's +/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); 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/app.rs b/apps/vectorcraft/src/app.rs index dddaf0a91e..a40eb0c92f 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -43,6 +43,16 @@ impl eframe::App for App { /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the /// app's raw-input hook while the keyboard user is unconfined. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + // Without vsync, a main-window frame starts no sooner than the minimum interval after the + // last one. eframe runs this hook once per frame, shown or not, before egui reads the input. + // The frame's time moves on by the wait, and the hang report's frame time starts after it. + if raw.viewport_id == egui::ViewportId::ROOT { + if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) { + std::thread::sleep(wait); + raw.time = raw.time.map(|time| time + wait.as_secs_f64()); + } + self.last_frame_began = Some(std::time::Instant::now()); + } let _timed = BEACON.enter_timed(Stage::Input); self.frame_start = Some(std::time::Instant::now()); // winit gives the window its caption back when it changes the window's flags (maximize, 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 2ed939245f..1ce124c1dd 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -73,7 +73,7 @@ fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { /// `d` set up for `request`: its title, file types, folder and suggested name. fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) => pick, + PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, PickRequest::OpenMany => { return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { d.filter( @@ -83,8 +83,9 @@ fn dialog_for(d: D, request: &PickRequest) -> D { }); } PickRequest::Folder => return d, + PickRequest::FolderAt(folder) => return d.folder(folder), }; - let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_)); + let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_)); let d = pick.filters.iter().fold(d, |d, (name, exts)| { d.filter( vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), @@ -95,7 +96,55 @@ 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)] +#[test] +fn a_folder_picker_asked_for_a_folder_starts_there() { + /// The settings a dialog was given, by name. + #[derive(Default)] + struct Recorded(Vec); + impl DialogSettings for Recorded { + fn parent(self, _: &winit::window::Window) -> Self { + self + } + fn title(mut self, title: &str) -> Self { + self.0.push(format!("title {title}")); + self + } + fn filter(mut self, name: &str, _: &[impl ToString]) -> Self { + self.0.push(format!("filter {name}")); + self + } + fn folder(mut self, folder: &str) -> Self { + self.0.push(format!("folder {folder}")); + self + } + fn file_name(mut self, name: &str) -> Self { + self.0.push(format!("name {name}")); + self + } + } + assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]); + assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty()); } /// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the @@ -130,9 +179,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) } let paths = match request { PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(), + PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(), PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder => dialog.pick_folder().into_iter().collect(), + PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(), }; paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() } @@ -315,7 +364,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti let picked = dialog.pick_file(); Box::pin(async move { picked.await.iter().map(path).collect() }) } - PickRequest::OpenMany => { + PickRequest::OpenMany | PickRequest::OpenFiles(_) => { let picked = dialog.pick_files(); Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) } @@ -334,7 +383,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti // on that nil; treat the pick as cancelled instead (#5980). Err(()) => Box::pin(async move { Vec::new() }), }, - PickRequest::Folder => { + PickRequest::Folder | PickRequest::FolderAt(_) => { let picked = dialog.pick_folder(); Box::pin(async move { picked.await.iter().map(path).collect() }) } @@ -355,7 +404,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .and_then(|w| w.window_handle().ok()) .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); let (clip, clip_probe) = (parent.clone(), parent.clone()); - let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); + let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); #[cfg(any(target_os = "macos", target_os = "linux", windows))] let sampled_ui = ui.clone(); #[cfg(target_os = "linux")] @@ -363,6 +412,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { Services { pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), + pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))), pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows // dialogs run the window's events while they are open. @@ -410,6 +460,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), + pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] screen_color: Some(mac_screen_color::sampler(sampled_ui)), @@ -762,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 { @@ -778,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 } } @@ -835,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/mac_tablet.rs b/apps/vectorcraft/src/mac_tablet.rs index 1d9aabd442..ade798a393 100644 --- a/apps/vectorcraft/src/mac_tablet.rs +++ b/apps/vectorcraft/src/mac_tablet.rs @@ -1,4 +1,5 @@ -//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764). winit 0.30 +//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764), and an airbrush +//! pen's finger wheel. winit 0.30 //! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit //! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas //! reads, as on X11 ([`crate::tablet`]). @@ -14,8 +15,9 @@ //! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the //! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read //! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation -//! from one held upright and unturned. Each reads as none until the pen reports a value other -//! than 0 after it comes near ([`Pen`]). +//! from one held upright and unturned. Its `tangentialPressure` (−1..1, an airbrush pen's finger +//! wheel) goes into the pose as the wheel, 0 for a pen without one as well. Each reads as none +//! until the pen reports a value other than 0 after it comes near ([`Pen`]). //! A mouse event of any other subtype is a mouse's or a trackpad's: the feed is set to `None`. //! - An `NSEventTypeTabletPoint` event carries the same pressure, tilt and rotation without a move. //! - A tablet proximity event (`NSEventTypeTabletProximity`, or a mouse event of that subtype) says @@ -68,6 +70,8 @@ struct RawEvent { tilt: (f64, f64), /// `rotation`, in degrees (the same events as `pressure`). rotation: f32, + /// `tangentialPressure`, −1..1 (the same events as `pressure`). + tangential: f32, /// `pointingDeviceType` (proximity events only). device: usize, /// `isEnteringProximity` (proximity events only). @@ -107,18 +111,42 @@ impl RawEvent { /// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the /// angle is negated and brought into 0..360. /// - /// The tilt is left out unless `tilts`, and the rotation unless `turns` ([`Pen`]). - fn pose(&self, tilts: bool, turns: bool) -> PenPose { + /// AppKit's `tangentialPressure` is −1.0..1.0, the finger wheel of an airbrush pen on the + /// devices that have one (). + /// It becomes [`PenPose`]'s wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is + /// clamped. + /// + /// The tilt is left out unless `read.tilts`, the rotation unless `read.turns`, and the wheel + /// unless `read.wheels` ([`Pen`]). + fn pose(&self, read: Reads) -> PenPose { let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32; // `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0. - let rotation = turns.then(|| (0.0 - self.rotation).rem_euclid(360.0)); - PenPose { tilt: tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation } + let rotation = read.turns.then(|| (0.0 - self.rotation).rem_euclid(360.0)); + let wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0); + PenPose { tilt: read.tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation, wheel } } - /// Whether the event reports a tilt other than 0, and a rotation other than 0. - fn reads(&self) -> (bool, bool) { + /// Whether the event reports a tilt other than 0, a rotation other than 0, and a tangential + /// pressure other than 0. + fn reads(&self) -> Reads { let read = |v: f64| v.is_finite() && v != 0.0; - (read(self.tilt.0) || read(self.tilt.1), read(f64::from(self.rotation))) + Reads { tilts: read(self.tilt.0) || read(self.tilt.1), turns: read(f64::from(self.rotation)), wheels: read(f64::from(self.tangential)) } + } +} + +/// Which of a pen's tilt, rotation and finger wheel it has reported. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Reads { + tilts: bool, + turns: bool, + wheels: bool, +} + +impl Reads { + fn add(&mut self, other: Reads) { + self.tilts |= other.tilts; + self.turns |= other.turns; + self.wheels |= other.wheels; } } @@ -148,14 +176,14 @@ impl Update { } } -/// Which end of the pen is near the tablet, and whether it has reported a tilt or a rotation other -/// than 0 since it came near: until it has, its tilt or rotation reads as none, since AppKit gives -/// 0 for a pen without one and for one held upright or unturned. +/// Which end of the pen is near the tablet, and whether it has reported a tilt, a rotation or a +/// tangential pressure other than 0 since it came near: until it has, that value reads as none, +/// since AppKit gives 0 for a pen without one and for one held upright, unturned or with its +/// wheel half way. #[derive(Clone, Copy, Debug, Default, PartialEq)] struct Pen { eraser: bool, - tilts: bool, - turns: bool, + read: Reads, } impl Pen { @@ -163,16 +191,14 @@ impl Pen { if e.proximity() { // Entering with the tip or the eraser end: it hovers. A puck, or leaving, is a mouse. self.eraser = e.entering && e.device == device::ERASER; - (self.tilts, self.turns) = (false, false); + self.read = Reads::default(); let pen = e.entering && e.device != device::CURSOR; return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() })); } if e.point() { - let (tilts, turns) = e.reads(); - self.tilts |= tilts; - self.turns |= turns; + self.read.add(e.reads()); } - let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.tilts, self.turns) }; + let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.read) }; match (e.point(), e.mouse()) { (true, true) => Update::Move(sample), (true, false) => Update::Set(Some(sample)), @@ -246,6 +272,7 @@ mod monitor { let tilt = e.tilt(); raw.tilt = (tilt.x, tilt.y); raw.rotation = e.rotation(); + raw.tangential = e.tangentialPressure(); } if raw.proximity() { raw.device = e.pointingDeviceType().0; @@ -326,26 +353,44 @@ mod tests { let sample = |pressure, pose| PenSample { pressure, eraser: false, pose }; assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet"); let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) }; - let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0) }; + let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0), wheel: None }; assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose))); let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) }; - let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0) }; + let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0), wheel: None }; assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped"); - let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") }; assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned"); assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}"); let feed = StylusFeed::default(); p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed); - assert_eq!(feed.pose(), Some(PenPose { tilt: None, rotation: Some(90.0) }), "a tilt that is not a number is left out"); + assert_eq!(feed.pose(), Some(PenPose { rotation: Some(90.0), ..PenPose::default() }), "a tilt that is not a number is left out"); p.handle(&proximity(1, true)); let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) }; - let pose = PenPose { tilt: Some([0.0, 30.0]), rotation: None }; + let pose = PenPose { tilt: Some([0.0, 30.0]), ..PenPose::default() }; assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near"); p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed); assert_eq!(feed.pose(), None, "a mouse moved"); } + /// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the feed as + /// 0..1, once the pen has reported a value other than 0 since it came near. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + let mut p = Pen::default(); + let wheel = |p: &mut Pen, tangential: f32| match p.handle(&RawEvent { tangential, ..pen(DRAG, 0.5) }) { + Update::Move(s) => s.pose.wheel, + u => panic!("a pen's drag is a move: {u:?}"), + }; + assert_eq!(wheel(&mut p, 0.0), None, "no wheel reported yet"); + assert_eq!(wheel(&mut p, -1.0), Some(0.0)); + assert_eq!(wheel(&mut p, 0.5), Some(0.75)); + assert_eq!(wheel(&mut p, 0.0), Some(0.5), "once reported, 0 is half way"); + assert_eq!(wheel(&mut p, 3.0), Some(1.0), "clamped"); + p.handle(&proximity(1, true)); + assert_eq!(wheel(&mut p, 0.0), None, "not reported since the pen came near"); + } + #[test] fn the_feed_gets_each_moves_pressure_within_0_to_1() { let feed = StylusFeed::default(); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index e7f50cb518..927b2899ae 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -142,6 +142,11 @@ struct App { display_profile: display_profile::Reader, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). frame_start: Option, + /// The shortest time between the starts of two frames, while the window presents without vsync + /// ([`presentation::min_frame_interval`]). + min_frame: Option, + /// When the last frame started, after its wait for [`Self::min_frame`]. + last_frame_began: Option, } /// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s. @@ -365,6 +370,10 @@ fn main() -> std::process::ExitCode { let saved_window = saved.as_ref().and_then(|ui| ui.window); #[cfg(feature = "wgpu")] let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str); + // Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off. + #[cfg(feature = "wgpu")] + let low_latency_drawing = + saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false); #[cfg(feature = "wgpu")] let power_env = eframe::wgpu::PowerPreference::from_env(); #[cfg(feature = "wgpu")] @@ -458,10 +467,11 @@ fn main() -> std::process::ExitCode { let mut options = options; // One frame queued, not two: the canvas is rasterized on the CPU and the GPU only // composites it, so the window answers the pointer a frame sooner (#444). - // `--present-mode` and `--frame-latency` change it for a launch (`presentation`). - options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY); + // `--present-mode` and `--frame-latency` change it for a launch, and Low-Latency Drawing + // asks for no vsync when neither sets the mode (`presentation`). + options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing); // What the app asks for: the driver picks novsync's mode and may clamp the latency. - log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation)); + log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation, low_latency_drawing)); // Only adapters that can show the window, in the order `gpu` gives (#306, #502). if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone())); @@ -508,6 +518,11 @@ fn main() -> std::process::ExitCode { // For the hang report (`hang_watch`). #[cfg(feature = "wgpu")] let requested_surface = options.wgpu_options.surface; + // Without vsync, frames start at most 240 times a second (`presentation`). + #[cfg(feature = "wgpu")] + let min_frame = presentation::min_frame_interval(&requested_surface); + #[cfg(not(feature = "wgpu"))] + let min_frame = None; // A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash. let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| { #[cfg(target_os = "linux")] @@ -539,6 +554,7 @@ fn main() -> std::process::ExitCode { // File Info's metadata templates live in their own folder next to the preferences. prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); + prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); @@ -696,6 +712,8 @@ fn main() -> std::process::ExitCode { monitors_listed: None, display_profile: Default::default(), frame_start: None, + min_frame, + last_frame_began: None, })) }), ) diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 2440037c10..5820240362 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -81,6 +81,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { } } +/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people +/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first +/// needs them. +pub fn attach_script_data(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Script Data") { + session.attach_script_data(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs index 7c2f1dc48a..76438ab996 100644 --- a/apps/vectorcraft/src/presentation.rs +++ b/apps/vectorcraft/src/presentation.rs @@ -6,9 +6,17 @@ //! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag //! overrides its variable; a value that isn't one of these stops the app with a message, as //! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`. -//! The surface the app asks for is logged at start-up. +//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at +//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the +//! surface presents without vsync, frames start at most 240 times a second. The surface the app +//! asks for is logged at start-up, with where its present mode came from. use std::ffi::OsString; +use std::time::Duration; + +/// The most frames a second the window draws while it presents without vsync. +#[cfg(feature = "wgpu")] +pub const UNSYNCED_FRAME_CAP: u32 = 240; /// A present mode the command line or the environment can ask for. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -96,25 +104,44 @@ impl Overrides { Ok(Self { mode, latency }) } - /// `surface` with the overrides applied. + /// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and + /// no present mode override, the mode is `novsync`. #[cfg(feature = "wgpu")] - pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig { + pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> eframe::egui_wgpu::SurfaceConfig { use eframe::wgpu::PresentMode; let present_mode = match self.mode { Some(Mode::Fifo) => PresentMode::Fifo, Some(Mode::AutoVsync) => PresentMode::AutoVsync, Some(Mode::NoVsync) => PresentMode::AutoNoVsync, + None if low_latency_drawing => PresentMode::AutoNoVsync, None => surface.present_mode, }; eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) } } } -/// The present mode and frame latency `surface` asks for, for the start-up log: -/// "autovsync, frame latency 1", with "(override)" -/// after a value a flag or variable set. +/// The shortest time between the starts of two frames on `surface`: `None` with vsync, where the +/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it. #[cfg(feature = "wgpu")] -pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String { +pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option { + use eframe::wgpu::PresentMode; + match surface.present_mode { + PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP), + PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None, + } +} + +/// How long a frame waits before it starts, `since_last` after the previous frame started, so that +/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed). +pub fn frame_wait(min: Option, since_last: Option) -> Option { + min?.checked_sub(since_last?).filter(|wait| !wait.is_zero()) +} + +/// The present mode and frame latency `surface` asks for, for the start-up log: +/// "autovsync, frame latency 1", with "(override)" after a value a flag or variable set, and +/// "(preference)" after a present mode Low-Latency Drawing set. +#[cfg(feature = "wgpu")] +pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> String { use eframe::wgpu::PresentMode; let mode = match surface.present_mode { PresentMode::AutoVsync => "autovsync", @@ -126,7 +153,8 @@ pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Override }; let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); let tag = |set: bool| if set { " (override)" } else { "" }; - format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some())) + let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) }; + format!("{mode}{mode_tag}, frame latency {latency}{}", tag(overrides.latency.is_some())) } #[cfg(test)] @@ -224,20 +252,99 @@ mod tests { use eframe::wgpu::PresentMode; let app = SurfaceConfig::LOW_LATENCY; // No override: the surface the app asks for is unchanged. - assert_eq!(Overrides::default().apply(app), app); + assert_eq!(Overrides::default().apply(app, false), app); let latency = Overrides { mode: None, latency: Some(2) }; - let s = latency.apply(app); + let s = latency.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2))); - assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)"); + assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)"); let fifo = Overrides { mode: Some(Mode::Fifo), latency: None }; - let s = fifo.apply(app); + let s = fifo.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency)); // Never a mode the driver may lack: no vsync lets wgpu fall back by support. let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; - let s = novsync.apply(app); + let s = novsync.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3))); - assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)"); + assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)"); let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None }; - assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default"); + assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default"); + } + + /// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an + /// explicit Immediate or Mailbox; off, the app's surface is exactly its own. + #[cfg(feature = "wgpu")] + #[test] + fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let none = Overrides::default(); + assert_eq!(none.apply(app, false), app); + let s = none.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoNoVsync); + assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency); + let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); + assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}")); + // A latency override still applies with the preference's mode. + let latency = Overrides { mode: None, latency: Some(2) }; + let s = latency.apply(app, true); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2))); + assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)"); + } + + /// The flag and the variable each set the present mode over Low-Latency Drawing. + #[cfg(feature = "wgpu")] + #[test] + fn the_flag_and_the_variable_win_over_low_latency_drawing() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let flag = parse(&["--present-mode", "fifo"]).unwrap(); + let s = flag.apply(app, true); + assert_eq!(s.present_mode, PresentMode::Fifo); + assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true)); + let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap(); + let s = var.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoVsync); + assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true)); + // The flag wins over the variable, and both over the preference. + let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap(); + assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo); + } + + /// Frames start at most 240 times a second without vsync, from the preference or an override, + /// and the display paces them with vsync. + #[cfg(feature = "wgpu")] + #[test] + fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let cap = Duration::from_secs(1) / 240; + assert_eq!(cap.as_nanos(), 4_166_666); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None); + for (mode, capped) in [ + (PresentMode::Immediate, true), + (PresentMode::Mailbox, true), + (PresentMode::AutoNoVsync, true), + (PresentMode::Fifo, false), + (PresentMode::FifoRelaxed, false), + (PresentMode::AutoVsync, false), + ] { + let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) }; + assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}"); + } + } + + #[test] + fn a_frame_waits_out_the_rest_of_the_minimum_interval() { + let min = Some(Duration::from_millis(4)); + assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3))); + assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None); + assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None); + assert_eq!(frame_wait(min, None), None, "the first frame starts at once"); + assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync"); } } 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/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs index ed4087e33e..f9371bd368 100644 --- a/apps/vectorcraft/src/tablet.rs +++ b/apps/vectorcraft/src/tablet.rs @@ -1,4 +1,5 @@ -//! Linux: a drawing tablet's pen pressure, tilt and barrel rotation under X11, XWayland included +//! Linux: a drawing tablet's pen pressure, tilt, barrel rotation and airbrush finger wheel under +//! X11, XWayland included //! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app //! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`] //! (`Services::stylus`), which the canvas reads. @@ -14,11 +15,17 @@ //! - "Abs Tilt X" and "Abs Tilt Y" (a pen that has both), in degrees as they are when the range //! fits in ±90, otherwise scaled to ±[`TILT_DEGREES`]; //! - "Abs Rotary Z" (the barrel rotation of an Art Pen), scaled to a turn with the middle of the -//! range at 0°. +//! range at 0°; +//! - "Abs Wheel" (the finger wheel of an airbrush pen), scaled from the valuator's range to 0..1. +//! XWayland also sends an Art Pen's barrel rotation on this valuator +//! (), so under +//! XWayland it reads as the wheel. A tablet pad's wheel is on a device without a pressure axis, +//! which is not read. //! //! Any other pointer device moving sets the feed to `None`. Raw events carry only the valuators //! that changed, so the last value of each axis of each pen is kept; an axis the pen has that no -//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing. +//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing. The +//! wheel reads nothing until an event carries it. //! //! The X server lists a pen's eraser end as a device of its own, whose name or XInput type contains //! "eraser" (xf86-input-wacom's "… Pen eraser" of type `ERASER`, xf86-input-libinput's @@ -60,6 +67,7 @@ enum AxisKind { TiltX, TiltY, Rotation, + Wheel, } impl AxisKind { @@ -70,6 +78,7 @@ impl AxisKind { "Abs Tilt X" => Some(Self::TiltX), "Abs Tilt Y" => Some(Self::TiltY), "Abs Rotary Z" => Some(Self::Rotation), + "Abs Wheel" => Some(Self::Wheel), _ => None, } } @@ -81,6 +90,7 @@ impl AxisKind { Self::TiltX => 1, Self::TiltY => 2, Self::Rotation => 3, + Self::Wheel => 4, } } } @@ -95,18 +105,22 @@ struct Axis { } impl Axis { - /// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90) or a - /// rotation in degrees (−180..180, the middle of the range at 0). A value that is not a number - /// is a mouse's pressure, 1, or a tilt or rotation of 0. + /// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90), a rotation + /// in degrees (−180..180, the middle of the range at 0) or a wheel of 0..1. A value that is not + /// a number is a mouse's pressure, 1, a tilt or rotation of 0, or a wheel half way. fn map(&self, v: f64) -> f32 { if !v.is_finite() { - return if self.kind == AxisKind::Pressure { 1.0 } else { 0.0 }; + return match self.kind { + AxisKind::Pressure => 1.0, + AxisKind::Wheel => 0.5, + _ => 0.0, + }; } let span = self.max - self.min; let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v }; let unit = unit.clamp(0.0, 1.0); match self.kind { - AxisKind::Pressure => unit as f32, + AxisKind::Pressure | AxisKind::Wheel => unit as f32, AxisKind::TiltX | AxisKind::TiltY if self.min >= -90.0 && self.max <= 90.0 && span > 0.0 => v.clamp(-90.0, 90.0) as f32, AxisKind::TiltX | AxisKind::TiltY => ((unit * 2.0 - 1.0) * TILT_DEGREES) as f32, AxisKind::Rotation => ((unit - 0.5) * 360.0) as f32, @@ -173,7 +187,7 @@ enum Update { #[derive(Debug, Default)] struct Pens { devices: HashMap, - last: HashMap; 4]>, + last: HashMap; 5]>, } impl Pens { @@ -200,10 +214,12 @@ impl Pens { } } } - // An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. + // An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. The + // wheel reads nothing until an event carries it: XWayland lists the axis for every pen. let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0)); let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]); - let pose = PenPose { tilt, rotation: value(AxisKind::Rotation) }; + let wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten()); + let pose = PenPose { tilt, rotation: value(AxisKind::Rotation), wheel }; Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose })) } @@ -430,7 +446,7 @@ mod tests { let mut pens = Pens::default(); pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]); let feed = StylusFeed::default(); - let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; pens.raw_event(&feed, 9, &[0b100], &[32767.5]); assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose }))); assert_eq!(feed.eraser(), Some(false)); @@ -479,10 +495,36 @@ mod tests { // A pen whose tilt and rotation no event has carried yet is upright and unturned. let mut fresh = Pens::default(); fresh.set_devices([pen(9)]); - let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright }))); } + /// An airbrush pen's "Abs Wheel" valuator goes into the feed as 0..1 of its range, once an + /// event carries it; a pen that lists it but has not moved it reads no wheel, and a device + /// without a pressure axis (a tablet pad's wheel) is not a pen. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + let mut valuators = pen_valuators(); + valuators.push((6, "Abs Wheel".to_string(), 0.0, 1023.0)); + let airbrush = Device::new(9, "Wacom Intuos Pro M Pen stylus", Some("STYLUS"), valuators); + let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(6, "Abs Wheel".to_string(), 0.0, 71.0)]); + let mut pens = Pens::default(); + pens.set_devices([airbrush, pad, pen(10)]); + let feed = StylusFeed::default(); + pens.raw_event(&feed, 9, &[0b100], &[32767.5]); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "no event has carried the wheel yet"); + pens.raw_event(&feed, 9, &[0b100_0000], &[255.75]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.25)); + pens.raw_event(&feed, 9, &[0b100_0000], &[5000.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "clamped to the range"); + pens.raw_event(&feed, 9, &[0b100], &[100.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "kept while other valuators move"); + pens.raw_event(&feed, 13, &[0b100_0000], &[30.0]); + assert_eq!((feed.held(), feed.pose()), (None, None), "the pad is not a pen"); + pens.raw_event(&feed, 10, &[0b100_0000], &[512.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a pen without the valuator"); + } + /// A device listed again unchanged keeps its last tilt and rotation; another device listed /// under the same id starts upright and unturned. #[test] @@ -495,7 +537,7 @@ mod tests { assert_eq!(pose.tilt, Some([-30.0, 45.0])); let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators()); pens.set_devices([other]); - let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright }))); } diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 5e996c4bdd..e1ea35104d 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -133,12 +133,13 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, po /// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is /// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the -/// rotation when it reports one, each kept within [`PenPose`]'s ranges. +/// rotation when it reports one, each kept within [`PenPose`]'s ranges. `POINTER_PEN_INFO` has no +/// field for an airbrush pen's finger wheel, so the pose has none. fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose { let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 }; let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]); let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32); - PenPose { tilt, rotation }.sanitized() + PenPose { tilt, rotation, wheel: None }.sanitized() } /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, @@ -426,12 +427,12 @@ mod tests { #[test] fn a_pens_tilt_and_rotation_come_where_it_reports_them() { let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; - assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) }); + assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None }); assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither"); - assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis"); - assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel"); + assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis"); + assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel"); let wild = pen_pose(all, 400, i32::MIN, 720); - assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges"); + assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0), wheel: None }, "kept within the ranges"); let pose = pen_pose(all, 10, 20, 180); assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose); } 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 0b48f586cd..d3dd3b6b38 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -160,7 +160,7 @@ impl Calligraphic { pub fn uses_pressure(&self) -> bool { self.modes().contains(&Variation::Pressure) } - /// Does the pen (its pressure, tilt, bearing or rotation) change the nib? + /// Does the pen (its pressure, tilt, bearing, rotation or wheel) change the nib? pub fn uses_pen(&self) -> bool { self.modes().iter().any(|m| m.follows_pen()) } @@ -202,11 +202,25 @@ pub enum Variation { /// The value plus the variation times the pen barrel's rotation over 180°, counter-clockwise /// from where the pen reports 0° round to ±180°. Rotation, + /// From the value less the variation with an airbrush pen's finger wheel at one end of its + /// travel to the value plus the variation at the other (the value itself half way). + StylusWheel, } impl Variation { - pub const ALL: [Variation; 6] = + pub const ALL: [Variation; 7] = + [Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; + /// The modes Brush Options offers for a value other than a size (a Calligraphic brush's Angle + /// and Roundness, a Scatter brush's Spacing, Scatter and Rotation): all but + /// [`Variation::StylusWheel`], which drives a Calligraphic or Scatter brush's Size and an Art + /// brush's Width. + pub const OTHER: [Variation; 6] = [Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation]; + /// The modes Brush Options offers for a size (`true`: [`Self::ALL`]) or another value + /// ([`Self::OTHER`]). + pub fn offered(size: bool) -> &'static [Variation] { + if size { &Self::ALL } else { &Self::OTHER } + } /// The name brush definitions use. pub fn id(self) -> &'static str { match self { @@ -216,6 +230,7 @@ impl Variation { Variation::Tilt => "tilt", Variation::Bearing => "bearing", Variation::Rotation => "rotation", + Variation::StylusWheel => "stylusWheel", } } pub fn label(self) -> &'static str { @@ -226,15 +241,16 @@ impl Variation { Variation::Tilt => "Tilt", Variation::Bearing => "Bearing", Variation::Rotation => "Rotation", + Variation::StylusWheel => "Stylus Wheel", } } pub fn parse(id: &str) -> Option { Self::ALL.into_iter().find(|v| v.id() == id) } /// Does the value follow something the pen records along a stroke (Pressure, Tilt, Bearing, - /// Rotation)? + /// Rotation, Stylus Wheel)? pub fn follows_pen(self) -> bool { - matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation) + matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation | Variation::StylusWheel) } } @@ -251,12 +267,14 @@ pub(crate) struct PenAt { bearing: f64, /// ½ plus the counter-clockwise barrel rotation over 360°. rotation: f64, + /// Where the airbrush finger wheel was set, 0 at one end of its travel to 1 at the other. + wheel: f64, } impl PenAt { /// Every input at `c`. pub(crate) fn uniform(c: f64) -> Self { - Self { pressure: c, tilt: c, bearing: c, rotation: c } + Self { pressure: c, tilt: c, bearing: c, rotation: c, wheel: c } } /// What `stroke` recorded at `f` (the fraction of its path's length). pub(crate) fn of(stroke: &StrokeLayer, f: f64) -> Self { @@ -267,6 +285,7 @@ impl PenAt { tilt: 1.0 - stroke.tilt.as_ref().map_or(mid, |p| p.at(f)), bearing: turn(stroke.bearing.as_ref()), rotation: turn(stroke.rotation.as_ref()), + wheel: stroke.wheel.as_ref().map_or(mid, |p| p.at(f)), } } /// The 0..1 a value on `mode` takes, or `None` for a mode that doesn't follow the pen. @@ -277,6 +296,7 @@ impl PenAt { Variation::Tilt => self.tilt, Variation::Bearing => self.bearing, Variation::Rotation => self.rotation, + Variation::StylusWheel => self.wheel, }; Some(if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 }) } @@ -298,12 +318,19 @@ 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, - /// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°). `None` - /// (brushes saved before there were modes): Random where the two differ, else Fixed (see - /// [`Scatter::modes`]). + /// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°), and Stylus + /// Wheel (the size's only) the first at one end of an airbrush pen's finger wheel and the + /// second at the other. `None` (brushes saved before there were modes): Random where the two + /// differ, else Fixed (see [`Scatter::modes`]). #[serde(skip_serializing_if = "Option::is_none")] pub modes: Option<[Variation; 4]>, } @@ -318,6 +345,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 +354,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] { @@ -375,11 +405,12 @@ pub struct ArtBrush { /// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the /// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure /// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing - /// and Rotation from −180° to 180° (half way at 0°). + /// and Rotation from −180° to 180° (half way at 0°), Stylus Wheel from one end of an airbrush + /// pen's finger wheel to the other. #[serde(skip_serializing_if = "Option::is_none")] pub width_mode: Option, - /// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or - /// at 180° (`width` without one). + /// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, at + /// 180° or at the wheel's far end (`width` without one). #[serde(skip_serializing_if = "Option::is_none")] pub width_max: Option, pub flip_along: bool, @@ -624,6 +655,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,11 +749,12 @@ 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) => { a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0); - // The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed. + // The width follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed. if !a.width_mode.is_some_and(Variation::follows_pen) { a.width_mode = None; } @@ -753,6 +789,229 @@ impl Brush { } } +// ---------- stroke options ---------- + +/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]). +#[derive(Serialize, Deserialize)] +struct ScatterOptions { + size: (f64, f64), + spacing: (f64, f64), + scatter: (f64, f64), + rotation: (f64, f64), + modes: Option<[Variation; 4]>, + rotation_relative_to_path: bool, + colorization: Colorization, +} + +/// The Art brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct ArtOptions { + width: f64, + width_mode: Option, + width_max: Option, + flip_along: bool, + flip_across: bool, + overlap: bool, + colorization: Colorization, +} + +/// The Pattern brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct PatternOptions { + scale: f64, + spacing: f64, + fit: PatternFit, + flip_along: bool, + flip_across: bool, + colorization: Colorization, +} + +impl BrushKind { + /// The definition fields, by their `brush.options` names, that one stroke can set for itself + /// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle + /// brush has none. + pub fn stroke_option_keys(&self) -> &'static [&'static str] { + match self { + BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"], + BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"], + BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], + BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Bristle(_) => &[], + } + } + + /// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the + /// values are a `null` `modes`, so a stroke that sets them so keeps that setting. + fn option_values(&self) -> serde_json::Value { + let v = match self { + BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| { + if let Some(o) = v.as_object_mut() { + o.entry("modes").or_insert(serde_json::Value::Null); + } + v + }), + BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions { + size: s.size, + spacing: s.spacing, + scatter: s.scatter, + rotation: s.rotation, + modes: s.modes, + rotation_relative_to_path: s.rotation_relative_to_path, + colorization: s.colorization, + }), + BrushKind::Art(a) => serde_json::to_value(ArtOptions { + width: a.width, + width_mode: a.width_mode, + width_max: a.width_max, + flip_along: a.flip_along, + flip_across: a.flip_across, + overlap: a.overlap, + colorization: a.colorization, + }), + BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { + scale: p.scale, + spacing: p.spacing, + fit: p.fit, + flip_along: p.flip_along, + flip_across: p.flip_across, + colorization: p.colorization, + }), + BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())), + }; + v.unwrap_or_default() + } + + /// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives + /// them). An error when a value is of the wrong kind. + fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> { + match self { + BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?, + BrushKind::Scatter(s) => { + let o: ScatterOptions = serde_json::from_value(v)?; + (s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes); + (s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization); + } + BrushKind::Art(a) => { + let o: ArtOptions = serde_json::from_value(v)?; + (a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across); + (a.overlap, a.colorization) = (o.overlap, o.colorization); + } + BrushKind::Pattern(p) => { + let o: PatternOptions = serde_json::from_value(v)?; + (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = + (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + } + BrushKind::Bristle(_) => {} + } + Ok(()) + } +} + +/// Stroke option value `new` with each `null` item of an array taken from the same place in +/// `current`, an array of the same length: a stroke option that changes some items of a range or a +/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as +/// it is. +pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value { + match (new, current) { + (serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => { + serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect()) + } + _ => new.clone(), + } +} + +impl Brush { + /// The brush as a stroke whose own settings are `options` draws it: each field of + /// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization` + /// object changes only the fields it gives), and the values are kept within their ranges + /// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there + /// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of + /// the wrong kind. + pub fn with_stroke_options(&self, options: &serde_json::Map) -> Result { + let keys = self.kind.stroke_option_keys(); + let mut values = self.kind.option_values(); + let Some(o) = values.as_object_mut() else { return Ok(self.clone()) }; + for (k, v) in options { + if !keys.contains(&k.as_str()) { + continue; + } + match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) { + (Some(inner), Some(fields)) if k == "colorization" => { + for (f, fv) in fields { + inner.insert(f.clone(), fv.clone()); + } + } + // Set below, once the values the modes may follow are in. + _ if k == "modes" => {} + _ => { + let current = o.get(k).cloned().unwrap_or_default(); + o.insert(k.clone(), keep_items(v, ¤t)); + } + } + } + // A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it. + if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut) + && c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift") + && c.get("key").is_none_or(serde_json::Value::is_null) + { + let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK); + c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?); + } + let mut b = self.clone(); + b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?; + if let Some(m) = options.get("modes") + && keys.contains(&"modes") + { + // A null item keeps the mode the brush with the other settings has: modes it leaves to + // its values follow the stroke's values, as they are kept within their ranges. Modes + // equal to those are left as the brush has them, so they keep following the values. + b.sanitize(); + let current = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(), + _ => serde_json::Value::Null, + }; + let modes = keep_items(m, ¤t); + if modes != current { + if let Some(o) = values.as_object_mut() { + o.insert("modes".into(), modes); + } + b = self.clone(); + b.kind.set_option_values(values).map_err(|e| e.to_string())?; + } + } + b.sanitize(); + Ok(b) + } + + /// The stroke options of `options` that make the brush draw differently: each field of + /// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs + /// from the brush's own, with that value (kept within its range). An error for a field the + /// type does not take and for a value of the wrong kind. + pub fn stroke_options_that_differ( + &self, + options: &serde_json::Map, + ) -> Result, String> { + let keys = self.kind.stroke_option_keys(); + if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) { + return Err(if keys.is_empty() { + format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase()) + } else { + format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", ")) + }); + } + let edited = self.with_stroke_options(options)?.kind.option_values(); + let own = self.kind.option_values(); + Ok(keys + .iter() + .filter_map(|k| { + let v = edited.get(*k)?; + (own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone())) + }) + .collect()) + } +} + // ---------- library ---------- /// The brush library of `doc`: its stored brushes, or the defaults when it has none. @@ -842,12 +1101,26 @@ fn tolerance(scale: f64) -> f64 { /// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id /// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush, /// and what they draw by name that would draw one is left out ([`leave_out_brushed`]). -/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). +/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own +/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values +/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is. pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec { + let edited; + let brush = if stroke.brush_options.is_empty() { + brush + } else { + match brush.with_stroke_options(&stroke.brush_options) { + Ok(b) => { + edited = b; + &edited + } + Err(_) => brush, + } + }; 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), @@ -856,6 +1129,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 } @@ -1008,6 +1287,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 de178c76ac..c7e4acc927 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1,3 +1,4 @@ +use serde_json::json; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes}; @@ -826,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); @@ -952,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] @@ -1305,6 +1545,64 @@ fn pressure_varies_angle_and_roundness() { assert!(near(h, expected, 0.05), "{h} vs {expected}"); } +/// A stroke that recorded an airbrush pen's finger wheel going from `from` to `to` along it. +fn wheeled(from: f64, to: f64) -> StrokeLayer { + StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, from), (1.0, to)] }), ..stroke(1.0) } +} + +/// Stylus Wheel: a Calligraphic brush's size goes from size − variation at one end of the finger +/// wheel to size + variation at the other, a Scatter brush's size from its first value to its +/// second, and an Art brush's width from Width to the second width. Each reads only the wheel: the +/// pressure, tilt, bearing or rotation recorded instead leaves the value half way. +#[test] +fn the_stylus_wheel_varies_sizes_and_widths() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 100.0, 0.0); + let c = Calligraphic { + size: 6.0, + variation: [0.0, 0.0, 4.0], + modes: Some([Variation::Fixed, Variation::Fixed, Variation::StylusWheel]), + ..Default::default() + }; + let nib = Brush { name: "w".into(), kind: BrushKind::Calligraphic(c) }; + let out = stroke_pieces(&doc, &nib, &bp, &wheeled(0.0, 1.0)); + // Round nib: 2 pt across at the start, 10 pt at the end, 6 pt half way. + assert!(near(half_width(&out, 0.5, 1.5), 1.0, 0.1), "{}", half_width(&out, 0.5, 1.5)); + assert!(near(half_width(&out, 98.5, 99.5), 5.0, 0.1), "{}", half_width(&out, 98.5, 99.5)); + assert!(near(half_width(&out, 49.5, 50.5), 3.0, 0.1), "{}", half_width(&out, 49.5, 50.5)); + let others = [ + pressed(vec![(0.0, 0.0), (1.0, 1.0)]), + StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }, + posed(None, Some(90.0), Some(-90.0)), + ]; + for st in &others { + let h = bounds(&stroke_pieces(&doc, &nib, &bp, st)).height(); + assert!(near(h, 6.0, 0.05), "{st:?}: {h}"); + } + // Scatter size 50 % to 300 % of 4 pt art: 2 pt at one end of the wheel, 12 pt at the other. + let spray = sized_scatter(50.0, 300.0, Variation::StylusWheel); + let h: Vec = + stroke_pieces(&doc, &spray, &line(0.0, 0.0, 400.0, 0.0), &wheeled(1.0, 0.0)).iter().map(|n| n.geometric_bounds().unwrap().height()).collect(); + assert!(near(h[0], 12.0, 0.2) && h[h.len() - 1] < 3.0, "{h:?}"); + // Art width 50 % to 300 % of 4 pt art. + let mut ribbon = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut ribbon.kind { + (a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::StylusWheel), Some(300.0)); + } + let out = stroke_pieces(&doc, &ribbon, &bp, &wheeled(1.0, 0.0)); + assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0)); + for st in &others { + let h = bounds(&stroke_pieces(&doc, &ribbon, &bp, st)).height(); + assert!(near(h, 7.0, 1e-6), "{st:?}: {h}"); + } + // A definition keeps the mode by name. + let lib = parse_library(&serde_json::json!([ + {"name": "a", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "stylusWheel", "width_max": 300.0}, + ])); + assert!(matches!(&lib[0].kind, BrushKind::Art(a) if a.width_mode == Some(Variation::StylusWheel))); +} + /// A stroke that recorded the pen's tilt (`tilt`: 0 upright to 1 flat), bearing and barrel /// rotation (degrees counter-clockwise), each the same all along it where given. fn posed(tilt: Option, bearing: Option, rotation: Option) -> StrokeLayer { @@ -1371,7 +1669,7 @@ fn bearing_and_rotation_turn_the_nib() { #[test] fn pen_modes_without_a_recording_draw_the_value_itself() { let horizontal = line(0.0, 0.0, 100.0, 0.0); - for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] { + for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] { let c = Calligraphic { angle: 90.0, roundness: 50.0, size: 10.0, variation: [90.0, 50.0, 6.0], modes: Some([mode; 3]) }; let b = Brush { name: "n".into(), kind: BrushKind::Calligraphic(c) }; let h = bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, &stroke(1.0))).height(); @@ -1418,7 +1716,7 @@ fn a_mouse_stroke_draws_pen_modes_as_pressure_did() { }; let (calli_before, scatter_before) = (calli(Variation::Pressure), scattered(Variation::Pressure)); assert!(!calli_before.is_empty() && !scatter_before.is_empty()); - for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] { + for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] { assert_eq!(calli(mode), calli_before, "{mode:?}"); assert_eq!(scattered(mode), scatter_before, "{mode:?}"); } @@ -1486,8 +1784,12 @@ fn brushes_without_modes_vary_randomly_as_before() { stroke_pieces(&Document::new(1.0, 1.0), &old, &bp, &pressed(vec![(0.0, 0.0), (1.0, 1.0)])) ); // Modes are saved by name. - assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation"])); - assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v))); + assert_eq!( + serde_json::to_value(Variation::ALL).unwrap(), + serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"]) + ); + assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id())); + assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel)); } /// Junk definitions and pressure never panic and never draw non-finite art. @@ -2037,3 +2339,100 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() { } } } + +/// `options` as a stroke's own brush settings. +fn with_options(options: serde_json::Value) -> StrokeLayer { + StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) } +} + +#[test] +fn a_strokes_own_options_change_its_art_and_leave_the_brush() { + let doc = Document::new(1.0, 1.0); + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let path = line(20.0, 50.0, 220.0, 50.0); + let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0}))); + assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half)); + assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush"); + let BrushKind::Art(a) = &brush.kind else { panic!("art brush") }; + assert_eq!(a.width, 100.0, "the brush keeps its width"); + // A calligraphic stroke's own size and angle. + let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0}))); + assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib)); + // A pattern stroke's own scale doubles the tiles across it. + let pattern = pattern_brush(PatternFit::Stretch, false); + let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height(); + let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height(); + assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}"); +} + +#[test] +fn stroke_options_are_checked_and_kept_within_their_ranges() { + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // Out of range: clamped; equal to the brush's own value: left out. + let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0})); + // A field the type does not take, and a value of the wrong kind, are errors. + assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle")); + assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err()); + let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err()); + assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty()); + // A colorization object changes only the fields it gives: Hue Shift keeps the key it has. + let key = Color::rgb(0.0, 0.0, 1.0); + let hue = Brush { + name: "h".into(), + kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }), + }; + let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap(); + assert_eq!(tints.kind.colorization(), Colorization::Tints); + let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + assert!(back.is_empty(), "the brush's own colorization: {back:?}"); + // Hue Shift without a key takes the art's main color, as brush.options gives it. + let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK); + assert_eq!(keyless["colorization"]["method"], json!("hueShift")); + assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap()); + // Settings that do not read draw the brush as it is. + let doc = Document::new(1.0, 1.0); + let path = line(20.0, 50.0, 220.0, 50.0); + let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]}))); + assert!(near(bounds(&odd).height(), 4.0, 1e-6)); +} + +#[test] +fn null_stroke_option_items_keep_the_items_the_stroke_has() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A scatter brush at fixed sizes, with no modes of its own: they follow its values. + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) }; + let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") }; + assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's"); + // A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode. + let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap(); + let BrushKind::Scatter(s) = e.kind else { panic!("scatter") }; + assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]); + // The kept modes follow the values as they are kept within their ranges. + let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap(); + let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]); + // Modes that change nothing are no setting of the stroke's: they keep following its values. + let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap(); + assert!(same.is_empty(), "{same:?}"); +} + +#[test] +fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A brush whose modes are its own, and a stroke whose modes follow its values instead. + let mut b = calli(0.0, 100.0, 3.0); + if let BrushKind::Calligraphic(c) = &mut b.kind { + c.modes = Some([Variation::Pressure; 3]); + } + let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0})); + let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give"); + // A brush whose modes follow its values: a null `modes` is the brush's own and is left out. + let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap(); + assert!(plain.is_empty(), "{plain:?}"); +} diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index bb397d7eaa..06ddc09b93 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -198,14 +198,24 @@ pub fn export(doc: &Document, opts: &HpglOptions) -> Result Ok(export_regions(doc, opts, &[opts.region])?.pop().unwrap_or_default()) } +/// An error unless a plot can cover `region`: its corners are finite and it has a width and a +/// height (either corner may come first). +pub fn check_region(region: Rect) -> Result<(), String> { + 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()); + } + Ok(()) +} + /// Write the visible art of `doc` over each of `regions` as an HP-GL plot, one per region, as /// [`export`] does with `opts.region`. The plots share one pen numbering, so a color is the same /// pen in each, and one point budget. pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> Result, String> { - let regions: Vec = regions.iter().map(|r| r.abs()).collect(); - if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) { - return Err("the export region is empty".into()); + for r in regions { + check_region(*r)?; } + let regions: Vec = regions.iter().map(|r| r.abs()).collect(); if !TOLERANCE_RANGE.contains(&opts.tolerance) { return Err("the curve tolerance must be from 0.01 to 10 points".into()); } 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..a851320907 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -127,8 +127,8 @@ impl Appearance { pub fn stroke_mut(&mut self) -> Option<&mut StrokeLayer> { self.items.iter_mut().rev().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }) } - /// This appearance for other art: the pen pressure, tilt, bearing and rotation its strokes - /// were drawn with stay with them. + /// This appearance for other art: the pen pressure, tilt, bearing, rotation and wheel its + /// strokes were drawn with stay with them. pub fn without_pressure(mut self) -> Self { for it in &mut self.items { if let AppearanceItem::Stroke(s) = it { @@ -136,6 +136,7 @@ impl Appearance { s.tilt = None; s.bearing = None; s.rotation = None; + s.wheel = None; } } self @@ -143,6 +144,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/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index f8a58758d8..1728b7e323 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -71,6 +71,11 @@ pub struct StrokeLayer { /// Brush applied to the stroke (by brush name). #[serde(default, skip_serializing_if = "Option::is_none")] pub brush: Option, + /// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush + /// definition fields, by their `brush.options` names, that replace the brush's values on this + /// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them. + #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] + pub brush_options: serde_json::Map, #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] pub opacity: f32, #[serde(default, skip_serializing_if = "crate::skip::is_default")] @@ -108,6 +113,11 @@ pub struct StrokeLayer { /// pressure, it stays with this path. #[serde(default, skip_serializing_if = "Option::is_none")] pub rotation: Option, + /// Where the finger wheel of an airbrush pen was set along the stroke: 0 at one end of its + /// travel to 1 at the other. Brushes with Stylus Wheel variation vary with it. Like the + /// pressure, it stays with this path. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wheel: Option, } /// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant @@ -170,6 +180,7 @@ impl StrokeLayer { arrow_scale: (100.0, 100.0), profile: None, brush: None, + brush_options: serde_json::Map::new(), opacity: 1.0, blend: BlendMode::Normal, visible: true, @@ -181,6 +192,7 @@ impl StrokeLayer { tilt: None, bearing: None, rotation: None, + wheel: None, } } /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index 3d89615016..e6f69e6670 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -130,8 +130,9 @@ impl WidthProfile { /// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1 /// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s -/// are. The pen's tilt is kept the same way ([`StrokeLayer::tilt`]). Calligraphic and Scatter -/// brushes with Pressure or Tilt variation read them; everything else ignores them. +/// are. The pen's tilt and an airbrush pen's finger wheel are kept the same way +/// ([`StrokeLayer::tilt`], [`StrokeLayer::wheel`]). Brushes with Pressure, Tilt or Stylus Wheel +/// variation read them; everything else ignores them. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PressureProfile { pub points: Vec<(f64, f64)>, diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index cb5f8fed66..caad4f6edc 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -188,7 +188,7 @@ fn angle_profiles_join_samples_the_shorter_way_round() { #[test] fn strokes_without_pressure_round_trip_unchanged() { let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap(); - for key in ["pressure", "tilt", "bearing", "rotation"] { + for key in ["pressure", "tilt", "bearing", "rotation", "wheel"] { assert!(json.get(key).is_none(), "{key}"); } let st: StrokeLayer = serde_json::from_value(json).unwrap(); @@ -199,19 +199,21 @@ fn strokes_without_pressure_round_trip_unchanged() { let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0); ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample()); assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None); - // The pen's tilt, bearing and rotation load, save and stay behind the same way. + // The pen's tilt, bearing, rotation and wheel load, save and stay behind the same way. let posed = StrokeLayer { tilt: Some(PressureProfile::sample()), bearing: Some(AngleProfile::sample()), rotation: Some(AngleProfile { points: vec![(0.0, -45.0)] }), + wheel: Some(PressureProfile { points: vec![(0.0, 0.25), (1.0, 0.75)] }), ..back }; + assert_eq!(serde_json::to_value(&posed).unwrap()["wheel"], serde_json::json!({"points": [[0.0, 0.25], [1.0, 0.75]]})); let again: StrokeLayer = serde_json::from_value(serde_json::to_value(&posed).unwrap()).unwrap(); assert_eq!(again, posed); let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0); *ap.stroke_mut().unwrap() = posed; let st = ap.without_pressure().stroke().cloned().unwrap(); - assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation), (None, None, None, None)); + assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation, st.wheel), (None, None, None, None, None)); } /// The Lens profile's widths at its middle, a quarter of the way along and past its end. diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index f8b62ac815..7c7429acc2 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -6,7 +6,7 @@ //! tool clicked. //! - **Paint**: colours, gradients (stops resampled to a common set when their counts differ), //! opacity, stroke weight, dashes, miter limit, width profiles and the pen pressure, tilt, -//! bearing and rotation that brushes read interpolate; what can't +//! bearing, rotation and wheel that brushes read interpolate; what can't //! (caps, joins, brushes, fonts, symbols, text content) switches halfway. //! - **Groups** pair their children in stacking order; the children one group has more of grow //! out of the other group's centre. Compound paths stay compound paths. @@ -429,8 +429,8 @@ fn lerp_angle(x: Option<&AngleProfile>, y: Option<&AngleProfile>, t: f64) -> Opt } /// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale, width -/// profile and the pen pressure, tilt, bearing and rotation its brush reads into `o` (a copy of -/// the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway). +/// profile and the pen pressure, tilt, bearing, rotation and wheel its brush reads into `o` (a +/// copy of the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway). fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) { let tf = t as f32; o.paint = lerp_paint(&x.paint, &y.paint, tf); @@ -444,6 +444,7 @@ fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) { o.tilt = lerp_pressure(x.tilt.as_ref(), y.tilt.as_ref(), t); o.bearing = lerp_angle(x.bearing.as_ref(), y.bearing.as_ref(), t); o.rotation = lerp_angle(x.rotation.as_ref(), y.rotation.as_ref(), t); + o.wheel = lerp_pressure(x.wheel.as_ref(), y.wheel.as_ref(), t); } /// Interpolate appearance stacks: item by item when their structure matches, else the top fill @@ -755,9 +756,9 @@ fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) { } /// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width -/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes, -/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as -/// they are. +/// profile (whose sides swap when reversed), pen pressure, tilt, bearing, rotation and wheel, its +/// dashes, a gradient along the path or across it (whose sides swap when reversed). Its arrowheads +/// stay as they are. fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) { if o.is_identity() { return; @@ -805,7 +806,7 @@ fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) { let out = reoriented(&pts, o, |f| p.at(f), |v| v, |(l, r)| (r, l)); p.points = out.into_iter().map(|(t, (l, r))| (t, l, r)).collect(); } - for p in [&mut s.pressure, &mut s.tilt].into_iter().flatten() { + for p in [&mut s.pressure, &mut s.tilt, &mut s.wheel].into_iter().flatten() { let out = reoriented(&p.points, o, |f| p.at(f), same, same); p.points = out; } @@ -842,8 +843,8 @@ fn reorient_strokes(n: &mut Node, o: Orient) { /// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths /// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its -/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and -/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are +/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing, +/// rotation and wheel then run the new way, so the stroke draws as it did. A compound path's subpaths are /// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns /// only when all of them turn alike. Arrowheads stay at the path's start and end. pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) { @@ -3014,6 +3015,48 @@ mod tests { assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation); } + #[test] + fn a_stylus_wheel_recording_turns_with_the_gradient_and_dashes_of_its_stroke() { + let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| { + let mut ap = Appearance::default(); + ap.set_stroke(Paint::solid(Color::BLACK)); + if let Some(s) = ap.stroke_mut() { + edit(s); + } + Node::path(NodeId(1), path, ap) + }; + let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke")); + let wheel = |s: &StrokeLayer, f: f64| s.wheel.as_ref().map_or(PressureProfile::MID, |p| p.at(f)); + let light = |s: &StrokeLayer, u: f32| match &s.paint { + Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::(), + p => panic!("a gradient: {p:?}"), + }; + let recorded = |s: &mut StrokeLayer| { + s.wheel = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + s.gradient_mode = StrokeGradientMode::Along; + s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false }); + }; + // An open key clicked at its last anchor: the wheel runs the other way with the gradient + // along it, and the dashes are read from its end. + let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false)); + let key = keyed(line(100.0), &recorded); + let s = stroke(&Lerp::new(&keyed(line(0.0), &|_| {}), &key, (None, Some(1))).at(1.0)); + assert!((wheel(&s, 0.0) - 1.0).abs() < 1e-9 && wheel(&s, 1.0).abs() < 1e-9, "{:?}", s.wheel); + assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{:?}", s.paint); + assert_ne!(s.dash, stroke(&key).dash, "the dashes turn too"); + // A closed key started half way round starts its wheel recording there, stepping where its + // own start was, as its gradient does. + let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)); + let key = keyed(square(100.0), &recorded); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0)); + assert!((wheel(&s, 0.25) - 0.75).abs() < 1e-9 && (wheel(&s, 0.75) - 0.25).abs() < 1e-9, "{:?}", s.wheel); + assert!((light(&s, 0.25) - 0.75).abs() < 0.02 && (light(&s, 0.75) - 2.25).abs() < 0.02, "{:?}", s.paint); + // Half way through, a key without a recording counts as the wheel half way. + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(0.5)); + assert!((wheel(&s, 0.25) - 0.625).abs() < 1e-9, "{:?}", s.wheel); + } + #[test] fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() { let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| { 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 7f26dc9a50..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, 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..ff8129426e 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::(); @@ -353,7 +354,8 @@ pub fn appearance_heap_bytes(a: &Appearance) -> usize { AppearanceItem::Stroke(s) => { s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern)) + s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points)) - + s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points)) + + [&s.pressure, &s.tilt, &s.wheel].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::() + + [&s.bearing, &s.rotation].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::() + s.brush.as_ref().map_or(0, String::capacity) } _ => 0, @@ -424,6 +426,27 @@ mod tests { d } + #[test] + fn every_pen_recording_of_a_stroke_counts() { + use crate::{AngleProfile, PressureProfile}; + let plain = Appearance::default_art(); + let base = appearance_heap_bytes(&plain); + let ramp = || PressureProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 0.5)).collect() }; + let turn = || AngleProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 10.0)).collect() }; + for i in 0..5 { + let mut a = plain.clone(); + let s = a.stroke_mut().unwrap(); + match i { + 0 => s.pressure = Some(ramp()), + 1 => s.tilt = Some(ramp()), + 2 => s.bearing = Some(turn()), + 3 => s.rotation = Some(turn()), + _ => s.wheel = Some(ramp()), + } + assert!(appearance_heap_bytes(&a) >= base + 100 * size_of::<(f64, f64)>(), "recording {i}"); + } + } + #[test] fn an_unchanged_copy_keeps_nothing_of_its_own() { let d = doc_with_rects(10); 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/text.rs b/crates/doc/src/text.rs index 6863960230..a07afd0843 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -32,8 +32,8 @@ pub use para_style::{ pub use runs::PATH_LEAD_MAX; pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias}; pub use tabs_lists::{ - Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, - TabStop, + Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, + TabAlign, TabStop, }; pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index c556f2f5b0..746c0b69d5 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -304,17 +304,40 @@ impl TextObject { /// Update the paragraph styles for replacing bytes `start..end` of the current plain text by /// `insert` (call before changing the runs). The paragraph the range starts in keeps its /// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that - /// style too (Return continues the paragraph it splits); later paragraphs keep theirs. + /// style too (Return continues the paragraph it splits), without the number its list gives it + /// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new + /// paragraphs is made at the start of a paragraph and some of that paragraph's text stays + /// after it, that number moves with the text to the last paragraph the insertion starts. pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) { - if self.paras.is_empty() { + let added = insert.bytes().filter(|&b| b == b'\n').count(); + let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some()); + // With one style for every paragraph, the new paragraphs take it as it is unless its list + // gives the paragraph a number. + if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) { return; } let r = self.paragraphs_in(start, end); let v = self.paragraph_styles(); - let Some(keep) = v.get(r.start).cloned() else { return }; - let added = insert.bytes().filter(|&b| b == b'\n').count(); + let Some(mut keep) = v.get(r.start).cloned() else { return }; + let given = keep.list.and_then(|l| l.start); + if let Some(l) = keep.list.as_mut() { + l.start = None; + } let mut out: Vec = v.iter().take(r.start + 1).cloned().collect(); out.extend(std::iter::repeat_n(keep, added)); + let text = self.plain_text(); + let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len())); + let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n')); + // The paragraph's text after the replaced bytes, which the last new paragraph then holds. + let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n'); + if given.is_some() && added > 0 && at_para_start && text_kept { + if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) { + l.start = None; + } + if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) { + l.start = given; + } + } out.extend(v.iter().skip(r.end).cloned()); self.paras = out; if let Some(first) = self.paras.first() { diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 62c6b8dd33..17325d071c 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -631,6 +631,8 @@ pub enum FirstBaseline { XHeight, /// The first line's leading. Leading, + /// The top of the first line's ideographic em box touches the frame top. + EmBoxHeight, /// Exactly `first_baseline_min` below the top. Fixed, } diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 26622fa115..2d62eb2f0d 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -206,15 +206,41 @@ pub struct ParaList { /// ([`Self::depth`]). The file saves it only when it is not 1. #[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")] pub level: u8, + /// The number a numbered paragraph is given, 1 to [`MAX_LIST_START`]: the numbered paragraphs + /// after it at its level count on from it ([`Self::next_marker`]). None: it counts on from the + /// numbered paragraph before it. A bulleted paragraph does not use it. A paragraph made + /// with Return in a paragraph that has one does not take it, and a paragraph style does not + /// keep it. A saved number outside the range is read as the nearest one. The file saves it + /// only when it is set. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "read_start")] + pub start: Option, } impl Default for ParaList { - /// A bulleted list with a dot, its marker aligned left, at level 1. + /// A bulleted list with a dot, its marker aligned left, at level 1, numbered on from the + /// paragraph before. fn default() -> Self { - Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 } + Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1, start: None } } } +/// The largest number a numbered paragraph can be given ([`ParaList::start`]). +pub const MAX_LIST_START: u32 = 999_999_999; + +/// Reads a saved list start, a whole number or null, as the nearest of 1 to [`MAX_LIST_START`], +/// so a start such as 0 or 5000000000 opens the file at 1 or [`MAX_LIST_START`]. Anything else +/// is an error. +fn read_start<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let start = match serde_json::Value::deserialize(d)? { + serde_json::Value::Null => return Ok(None), + serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => { + n.as_i64().map_or(i64::from(MAX_LIST_START), |n| n.clamp(1, i64::from(MAX_LIST_START))) + } + _ => return Err(serde::de::Error::custom("a list start must be a whole number")), + }; + Ok(u32::try_from(start).ok()) +} + /// Is `level` the first list level, which the file does not save? fn is_first_level(level: &u8) -> bool { *level == 1 @@ -307,6 +333,12 @@ impl ParaList { Self { level, ..self } } + /// This list with the paragraph numbered `start` (1 to [`MAX_LIST_START`]; None: on from the + /// paragraph before). + pub fn starting_at(self, start: Option) -> Self { + Self { start, ..self } + } + /// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken /// as the nearest level. pub fn depth(&self) -> usize { @@ -334,8 +366,9 @@ impl ParaList { /// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts /// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1 /// again; a bulleted one has its bullet and leaves the count of its level as it is, and a - /// numbered one adds one to the count of its level and is numbered with it. A paragraph back - /// at a shallower level then goes on with that level's count. + /// numbered one adds one to the count of its level and is numbered with it, or with the number + /// it is given ([`Self::start`]), which becomes the count of its level. A paragraph back at a + /// shallower level then goes on with that level's count. pub fn next_marker(list: Option, empty: bool, counts: &mut ListCounts) -> Option { let Some(list) = list else { *counts = ListCounts::default(); @@ -350,7 +383,7 @@ impl ParaList { } let count = &mut counts.0[level]; if list.number.is_some() { - *count = count.saturating_add(1); + *count = list.start.map_or_else(|| count.saturating_add(1), |s| s.clamp(1, MAX_LIST_START)); } Some(list.marker(*count)) } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index a5230d5d86..63b763423d 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -456,6 +456,99 @@ fn list_levels_count_their_own_numbers_and_save_only_past_the_first() { assert_eq!(opened.list_level_counts, (1..=8).collect::>(), "a file keeps only the counts of levels 2 to 9"); } +/// A numbered paragraph given a number shows it, and the numbered paragraphs after it at its level +/// count on from it; deeper levels still count from 1 after it, a bulleted or empty paragraph does +/// not use the number, and a paragraph in no list still starts the count again. The file saves the +/// number only when it is set, and a saved number outside 1 to 999999999 reads as the nearest one. +#[test] +fn a_numbered_paragraph_given_a_number_starts_its_level_count_there() { + let num = |level, start| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level).starting_at(start)); + let dot = Some(ParaList::bulleted(Bullet::Dot).starting_at(Some(7))); + let mut counts = ListCounts::default(); + let markers: Vec> = [ + (num(1, None), false), + (num(1, Some(5)), false), + (num(1, None), false), + (num(2, None), false), + (num(2, Some(1)), false), + (num(2, None), false), + (num(1, None), false), + (num(1, Some(9)), true), + (num(1, None), false), + (dot, false), + (num(1, Some(1)), false), + (None, false), + (num(1, None), false), + ] + .iter() + .map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts)) + .collect(); + let want = ["1.", "5.", "6.", "1.", "1.", "2.", "7.", "", "8.", "\u{2022}", "1.", "", "1."]; + assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::>(), want); + let mut counts = ListCounts::default(); + let roman = Some(ParaList::numbered(NumberStyle::UpperRoman).starting_at(Some(MAX_LIST_START))); + assert_eq!(ParaList::next_marker(roman, false, &mut counts).as_deref(), Some("999999999.")); + let zero = Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(0))); + assert_eq!(ParaList::next_marker(zero, false, &mut counts).as_deref(), Some("1."), "a number below 1 counts as 1"); + assert_eq!(serde_json::to_value(num(1, None)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic"})); + assert_eq!(serde_json::to_value(num(1, Some(5))).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "start": 5})); + let read = |v: serde_json::Value| serde_json::from_value::(v).unwrap().start; + assert_eq!(read(serde_json::json!({"number": "arabic", "start": 5})), Some(5)); + assert_eq!(read(serde_json::json!({"number": "arabic"})), None); + assert_eq!(read(serde_json::json!({"number": "arabic", "start": null})), None); + let starts = [serde_json::json!(0), serde_json::json!(-3), serde_json::json!(5_000_000_000_u64), serde_json::json!(u64::MAX)]; + assert_eq!( + starts.map(|s| read(serde_json::json!({ "number": "arabic", "start": s }))), + [Some(1), Some(1), Some(MAX_LIST_START), Some(MAX_LIST_START)], + "a saved number outside 1 to 999999999 reads as the nearest one" + ); + for bad in [serde_json::json!(2.5), serde_json::json!("5"), serde_json::json!(true)] { + assert!(serde_json::from_value::(serde_json::json!({ "start": bad })).is_err(), "{bad}"); + } +} + +/// Return in a paragraph that its list gives a number makes paragraphs without it, also while +/// every paragraph shares one style; Return at the start of its text moves the number with the +/// text, and Return elsewhere leaves it where it was. +#[test] +fn return_does_not_copy_a_paragraphs_number() { + let five = ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(5))), ..ParaStyle::default() }; + let starts = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::>(); + // One style for the whole text: Return after "one" splits it. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(five); + t.splice_paras(3, 3, "\n"); + t.runs[0].text.insert(3, '\n'); + t.normalize_paras(); + assert_eq!(starts(&t), [Some(5), None]); + assert!(t.para_at(1).list.is_some_and(|l| l.number == Some(NumberStyle::Arabic)), "the new paragraph stays in the list"); + // Return at the start of "two" (a paragraph with a number of its own): the number moves on + // with the text, and the empty paragraph left before it has none. + t.edit_paras(Some(1..2), |p| p.list = p.list.map(|l| l.starting_at(Some(8)))); + t.splice_paras(4, 4, "\n\n"); + t.runs[0].text.insert_str(4, "\n\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, Some(8)]); + // A whole paragraph pasted at the start of "two": the number stays with "two". + t.splice_paras(6, 6, "Pasted\n"); + t.runs[0].text.insert_str(6, "Pasted\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8)]); + // "two" replaced by two paragraphs: none of its text is left, so the first new one keeps it. + t.splice_paras(13, 16, "A\nB"); + t.runs[0].text.replace_range(13..16, "A\nB"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\nA\nB"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8), None]); + // Text without a number keeps one style for every paragraph. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), ..ParaStyle::default() }); + t.splice_paras(3, 3, "\n"); + assert!(t.paras.is_empty()); +} + /// In a threaded frame whose first paragraph continues from the frame before, the text at the /// frame's start is not the start of a paragraph, so typing a list's start there starts nothing. /// The paragraphs after it still start lists. @@ -554,6 +647,20 @@ fn text_flow_is_saved_only_when_by_rows() { assert!(serde_json::from_value::(serde_json::json!({"flow": "diagonal"})).is_err()); } +/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from +/// before it read their own first baseline as they did, Ascent when they have none. +#[test] +fn em_box_height_first_baseline_is_saved_and_read_back() { + let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() }; + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0))); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0}); + assert_eq!(serde_json::from_value::(old).unwrap().first_baseline, FirstBaseline::Leading); + assert_eq!(serde_json::from_value::(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent); + assert!(serde_json::from_value::(serde_json::json!({"firstBaseline": "emBox"})).is_err()); +} + /// 120 × 40 area type at (40, 40), its text drawn at twice its size. fn area_type() -> TextObject { let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 5fabfece65..728c8aa816 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -81,6 +81,21 @@ impl Unit { Unit::Ha => "H", } } + /// Whether this unit is a physical measurement unit (not points or pixels). + pub fn is_physical(self) -> bool { + self.svg_suffix().is_some() || matches!(self, Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet | Unit::Q | Unit::Ha) + } + /// The standard SVG length unit suffix, if this unit is a physical unit supported in SVG + /// (`mm`, `cm`, `in`, `pc`). + pub fn svg_suffix(self) -> Option<&'static str> { + match self { + Unit::Millimeters => Some("mm"), + Unit::Centimeters => Some("cm"), + Unit::Inches => Some("in"), + Unit::Picas => Some("pc"), + _ => None, + } + } pub const fn label(self) -> &'static str { match self { Unit::Points => "Points", @@ -157,12 +172,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 +235,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"). @@ -316,10 +376,42 @@ fn percent(s: &str) -> Option { } } +/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` +/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed +/// after the value the field shows) is 100 mm (#5684). A number written with both separators has +/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a +/// number that reads as thousands ([`thousands`]). +pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { + if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } +} + +/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or +/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at +/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it +/// instead (`0,125` and `1,25` are decimals). +fn thousands(text: &str) -> bool { + let number = text.trim(); + let number = number.strip_prefix(['+', '-']).unwrap_or(number); + let Some((whole, rest)) = number.split_once(',') else { return false }; + let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); + (1..=3).contains(&whole.len()) + && whole.bytes().all(|b| b.is_ascii_digit()) + && !whole.starts_with('0') + && part.len() == 3 + && unit.trim().chars().all(|c| c.is_alphabetic() || c == '"' || c == '\'') +} + +/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length +/// near the largest number in points is too large in Q and Ha. +pub fn finite_in_every_unit(pt: f64) -> bool { + pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite()) +} + /// 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 fb2c5b1fea..d089fa0a22 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; or custom, a bevel of the user's own drawn by bevelProfile), 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), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), 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; or custom, a bevel of the user's own drawn by bevelProfile), 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), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), 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 1f1cfe82e7..23f3f478f9 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 d4e7a56b82..874b502f24 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; @@ -93,11 +93,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) } @@ -238,6 +241,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surface: false, } } @@ -314,6 +318,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. @@ -400,7 +454,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"); @@ -417,7 +472,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 @@ -431,6 +487,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 @@ -475,7 +555,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(|_| ()) @@ -749,6 +829,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) @@ -863,7 +967,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. @@ -874,7 +978,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, @@ -882,6 +988,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>> { @@ -895,7 +1002,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; } @@ -907,6 +1014,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 { @@ -1159,6 +1267,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)?)) @@ -1837,6 +1947,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; @@ -1879,9 +1995,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)) => { @@ -1891,8 +2011,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. @@ -1976,6 +2100,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)| { @@ -1983,10 +2110,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) }) @@ -2300,8 +2439,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())?; @@ -2325,6 +2474,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; } @@ -2350,10 +2505,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 129704a834..05973ea321 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 4e07b323c1..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 } @@ -70,8 +73,9 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } -# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`). -# Already in Cargo.lock (walkdir), so this adds no new crate. +# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`), +# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock +# (walkdir), so this adds no new crate. [target.'cfg(windows)'.dependencies] same-file = "1.0.6" 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 1c4a764a47..8edc028935 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -33,6 +33,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; @@ -75,6 +76,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; @@ -99,12 +101,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; @@ -323,6 +326,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()); @@ -335,6 +339,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()); @@ -384,6 +389,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()); @@ -409,7 +415,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 @@ -823,12 +840,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; @@ -861,10 +882,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`). @@ -888,6 +913,11 @@ 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; + /// The gaps View › Show Live Paint Gaps shows on a Live Paint group. pub use buildcmds::live_paint_gaps; @@ -903,6 +933,10 @@ pub use brushsym::current_symbol; /// Data window reads files by it too). pub use variablecmds::utf16_order_without_mark; +/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data +/// file: its size limit, its text, its cells and the data `graph.setData` takes from them. +pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; + /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 8c310878fd..03fb17f436 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -14,8 +14,10 @@ mod pen; mod select; mod shapes; 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; @@ -35,5 +37,6 @@ pub fn specs() -> Vec { v.extend(select::specs()); v.extend(shapes::specs()); v.extend(typetools::specs()); + v.extend(units::specs()); v } 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 new file mode 100644 index 0000000000..4da4f68b79 --- /dev/null +++ b/crates/engine/src/cmd/addons/units.rs @@ -0,0 +1,124 @@ +//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. +//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and +//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). +//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform +//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the +//! UI's; the panel applies a length to the selection with `object.setBounds`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +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}; +use crate::{Result, Session}; + +const CONVERT: &str = "addon.units.convert"; +const SELECTION_SIZE: &str = "addon.units.selectionSize"; +/// The most characters of a refused value an error message shows. +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`, a multiplication sign +/// counted as a `*`: [`Unit::parse`] takes one level of recursion per sign. +const MAX_OPERATORS: usize = 128; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "addon.units.convert", + "Convert Units", + [], + None, + "{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 + ), + cmd!( + query "addon.units.selectionSize", + "Selection Size in Units", + [], + None, + "{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}", + has_selection, + selection_size + ), + ] +} + +/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit, +/// label, number, text}]}`. +pub fn in_every_unit(pt: f64) -> Value { + let units: Vec = + Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect(); + json!({ "points": pt, "units": units }) +} + +/// The unit `p` gives for a number without a suffix (points when left out; null is an error). +fn unit_param(p: &Value) -> Result { + let Some(given) = p.get("unit") else { return Ok(Unit::Points) }; + let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian); + named.ok_or_else(|| { + let u = match given { + Value::String(s) => clipped(s).escape_debug().to_string(), + other => shown(other), + }; + bad(CONVERT, format!("unknown units `{u}`")) + }) +} + +fn convert(_: &mut Session, p: &Value) -> Result { + let unit = unit_param(p)?; + let Some(v) = p.get("value").filter(|v| !v.is_null()) else { + return Err(bad(CONVERT, "missing `value`")); + }; + let pt = match v { + Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), + _ => None, + }; + let pt = pt.filter(|&pt| finite_in_every_unit(pt)); + pt.map(in_every_unit).ok_or_else(|| { + let v = shown(v); + bad(CONVERT, format!("`value` must be a number, not {v}")) + }) +} + +/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /` +/// signs, a multiplication sign typed as `x`, `X` or `×` counted as a `*` ([`arithmetic_signs`])? +fn readable(s: &str) -> bool { + 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, +/// an array as `[…]` and an object as `{…}`. +fn shown(v: &Value) -> String { + match v { + Value::String(s) => Value::String(clipped(s)).to_string(), + Value::Array(_) => "[…]".into(), + Value::Object(_) => "{…}".into(), + other => other.to_string(), + } +} + +/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer. +fn clipped(s: &str) -> String { + match s.char_indices().nth(SHOWN_CHARS) { + Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()), + None => s.to_string(), + } +} + +fn selection_size(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let measure = s.bounds_measure(); + let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) { + Some(r) => Some(OrientedBox::aligned(r)), + None => s.transform_box(&st.selection.objects), + }; + let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?; + Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) })) +} diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs new file mode 100644 index 0000000000..802fb5dfdf --- /dev/null +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -0,0 +1,215 @@ +//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's +//! size as the Transform panel measures it, bad params refused, and nothing in the document changed. + +use serde_json::{Value, json}; +use vectorcraft_doc::Unit; + +use crate::{EngineError, Session}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn convert(s: &mut Session, p: Value) -> Value { + s.execute("addon.units.convert", &p).unwrap() +} + +/// The row of `r` for the unit with key `key`. +fn row<'a>(r: &'a Value, key: &str) -> &'a Value { + r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}")) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn a_length_comes_back_in_every_unit_in_order() { + let mut s = session(); + let r = convert(&mut s, json!({"value": "10mm"})); + assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4)); + let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect(); + assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key)); + assert_eq!(row(&r, "millimeters")["number"], "10"); + assert_eq!(row(&r, "millimeters")["text"], "10 mm"); + assert_eq!(row(&r, "centimeters")["text"], "1 cm"); + assert_eq!(row(&r, "inches")["text"], "0.3937 in"); + assert_eq!(row(&r, "points")["text"], "28.346 pt"); + assert_eq!(row(&r, "q")["text"], "40 Q"); + assert_eq!(row(&r, "ha")["text"], "40 H"); + assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points"); + assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches"); + // Each row is what a field of that unit shows for the length. + for u in Unit::EAST_ASIAN { + let pt = 720.0 / 25.4; + assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}"); + assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}"); + } +} + +#[test] +fn values_read_as_number_fields_read_them() { + let mut s = session(); + let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); + assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0)); + assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0)); + assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6)); + // A number without a unit is in `unit`, points by default. + assert!(near(pt(&mut s, json!({"value": 12})), 12.0)); + assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6)); + assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0)); + // A suffix wins over `unit`. + assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0)); + // A decimal comma reads as a point, as in the number fields. + assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); + // Each number of a sum reads its own separator. + assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); + // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. + 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] +fn keys_the_commands_do_not_take_are_refused() { + let s = session(); + s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap(); + s.check_params("addon.units.selectionSize", &json!({})).unwrap(); + for (id, p) in [ + ("addon.units.convert", json!({"value": 1, "units": "mm"})), + ("addon.units.convert", json!({"value": 1, "ids": [1]})), + ("addon.units.selectionSize", json!({"ids": [1]})), + ("addon.units.selectionSize", json!({"value": 1})), + ] { + match s.check_params(id, &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"), + other => panic!("{id} {p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_follows_preview_bounds_and_selected_anchors() { + let mut s = session(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap(); + let wh = |s: &mut Session| { + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) + }; + assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds"); + // Use Preview Bounds: the stroke's outer half on every side. + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let (w, h) = wh(&mut s); + assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}"); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap(); + // Two neighboring anchors selected (Direct Selection): the box around them, one edge of the + // rectangle. + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let (w, h) = wh(&mut s); + assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}"); +} + +#[test] +fn it_needs_no_document_and_changes_nothing() { + let mut s = Session::new(); + assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0)); + let mut s = session(); + let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + convert(&mut s, json!({"value": "5mm"})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn bad_values_and_units_are_refused() { + let mut s = session(); + for p in [ + json!({}), + json!({"value": null}), + json!({"value": "abc"}), + json!({"value": "10 furlongs"}), + json!({"value": "1in/0"}), + json!({"value": "1e400"}), + // Finite in points, too large in Q and Ha. + json!({"value": 1.5e308}), + json!({"value": "1.5e308"}), + // A thousands comma is refused, as the number fields refuse it. + json!({"value": "1,000 mm"}), + json!({"value": "1,000.5"}), + json!({"value": "+1,000"}), + json!({"value": "1,000\""}), + json!({"value": "1,000'"}), + // A long expression is refused instead of exhausting the stack. + json!({"value": format!("1{}", "+1".repeat(200_000))}), + json!({"value": format!("1{}", "+1".repeat(129))}), + json!({"value": true}), + json!({"value": [1]}), + json!({"value": 1, "unit": "furlongs"}), + json!({"value": 1, "unit": 5}), + json!({"value": 1, "unit": ["mm"]}), + // Only an omitted `unit` is points. + json!({"value": 1, "unit": null}), + ] { + match s.execute("addon.units.convert", &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"), + other => panic!("{p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn a_long_value_or_unit_is_refused_with_a_short_message() { + let mut s = session(); + let long = "9".repeat(100_000); + for (p, says) in [ + (json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))), + (json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()), + (json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))), + (json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()), + (json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()), + ] { + match s.execute("addon.units.convert", &p) { + Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"), + other => panic!("expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_is_the_transform_panels() { + let mut s = session(); + assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected"); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(row(&r["width"], "inches")["text"], "1 in"); + assert_eq!(row(&r["height"], "picas")["text"], "3 p"); + // A turned object keeps its own sides, as the Transform panel's W and H show them. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width())); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step"); +} 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 c4f35dfc3f..ae0a721b4e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -36,8 +36,8 @@ mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; use brushes::{ - brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art, - brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, + brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, + brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; @@ -165,10 +165,19 @@ 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|stylusWheel 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°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; 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|stylusWheel 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°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), 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|stylusWheel, 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°; stylusWheel: width at one end of the finger wheel to width_max at the other; 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 ), + cmd!( + "brush.objectOptions", + "Options of Selected Object…", + [], + None, + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + has_doc, + brush_object_options + ), cmd!( "object.expandBrush", "Expand Brush Strokes", @@ -202,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 ), @@ -256,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 7a92ff130a..b0ab4366d2 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -1,6 +1,7 @@ use super::{ AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value, anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param, + switch_or, }; // ---------- brushes ---------- @@ -31,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`]). @@ -57,6 +63,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke: st.width = 1.0; } st.brush = Some(name.to_string()); + // The path's own brush settings (Options of Selected Object) go with the brush they set. + st.brush_options.clear(); } } } @@ -85,6 +93,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result { for it in &mut n.appearance.items { if let AppearanceItem::Stroke(st) = it { st.brush = None; + st.brush_options.clear(); } } } @@ -129,13 +138,17 @@ fn merge(base: &mut Value, patch: &Value) { } } -/// Sets brush `to` on the strokes in `items` that paint with brush `from`. +/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps +/// each stroke's own settings for it; a stroke left without a brush loses them. fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) { for it in items { if let AppearanceItem::Stroke(st) = it && st.brush.as_deref() == Some(from) { st.brush = to.map(str::to_string); + if to.is_none() { + st.brush_options.clear(); + } } } } @@ -494,6 +507,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { Ok(json!({ "name": out })) } +/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths +/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's +/// own settings, `reset` clears them; without either, nothing changes and the settings are given. +pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.objectOptions"; + let params = match p.get("params") { + None | Some(Value::Null) => serde_json::Map::new(), + Some(Value::Object(o)) => o.clone(), + Some(_) => { + let key = "params"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let reset = switch_or(p, "reset", false, C)?; + if reset && !params.is_empty() { + return Err(bad(C, "give `params` or `reset`, not both")); + } + let d = &s.doc()?.doc; + let lib = brush::library(d); + let ids = brush_targets(d, &roots(s, p)?); + // Each brushed stroke: its path, its place in the appearance, its brush and its settings now. + let mut strokes = vec![]; + for id in &ids { + let Some(n) = d.node(*id) else { continue }; + for (i, it) in n.appearance.items.iter().enumerate() { + let AppearanceItem::Stroke(st) = it else { continue }; + if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) { + strokes.push((*id, i, b, &st.brush_options)); + } + } + } + let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) }; + if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) { + return Err(bad(C, "the selected paths are painted with brushes of different types")); + } + // Only a bristle brush has none. + if first.kind.stroke_option_keys().is_empty() { + return Err(bad(C, "a bristle brush has no options of its own on a path")); + } + let out: Vec = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect(); + // Without params or reset the settings are only given: nothing is normalized or changed. + if !reset && params.is_empty() { + let keys = first.kind.stroke_option_keys(); + let own: serde_json::Map = + strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own })); + } + let mut changes = vec![]; + let mut options = None; + for (id, i, b, own) in &strokes { + let next = if reset { + serde_json::Map::new() + } else { + // Settings saved for another type of brush are left out. + let keys = b.kind.stroke_option_keys(); + let mut merged: serde_json::Map = + own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + let was = merged.clone(); + // A colorization object changes only the fields it gives, and a null item of an + // array keeps the stroke's own item (else the brush's). + for (k, v) in ¶ms { + let next = match (merged.get(k), v) { + (Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => { + let mut c = mine.clone(); + c.extend(fields.clone()); + Value::Object(c) + } + (Some(mine), _) => brush::keep_items(v, mine), + (None, _) => v.clone(), + }; + merged.insert(k.clone(), next); + } + keep_drawn_modes(b, &was, ¶ms, &mut merged); + keep_largest_width(b, &was, ¶ms, &mut merged); + b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? + }; + options.get_or_insert_with(|| next.clone()); + if &next != *own { + changes.push((*id, *i, next)); + } + } + let changed: Vec = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect(); + if !changes.is_empty() { + s.edit("Options of Selected Object", |d, _| { + for (id, i, next) in changes { + if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) { + st.brush_options = next; + } + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() })) +} + +/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush. +fn drawn_modes(b: &Brush) -> Option> { + let modes = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()), + _ => return None, + }; + match modes { + Ok(Value::Array(m)) => Some(m), + _ => None, + } +} + +/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params` +/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`, +/// would change. A mode the stroke leaves to its values follows them, so without this a changed +/// variation or range would also change the mode. +fn keep_drawn_modes( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + let given = match params.get("modes") { + None | Some(Value::Null) => vec![], + Some(Value::Array(m)) => m.clone(), + // A value of the wrong kind is refused when the settings are checked. + Some(_) => return, + }; + let (Some(before), Some(after)) = + (b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes)) + else { + return; + }; + if before == after { + return; + } + let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect(); + merged.insert("modes".into(), Value::Array(kept)); +} + +/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when +/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is +/// the width, so without this a changed width would also change the largest width. +fn keep_largest_width( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + return; + } + let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some(a), + _ => None, + }; + let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; + let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); + // Only a width that followed the pen has a largest width, and only one that still does uses it. + if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { + merged.insert("width_max".into(), json!(before.width)); + } +} + /// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it /// places them; `brush.replaceArt` reads a group of that name as that tile. const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; 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 a15af16360..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; @@ -659,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) { } s.profile = None; s.brush = None; + s.brush_options.clear(); } if !starts { s.start_arrow = None; 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/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f912fce7ae..0a98ddd9bc 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -579,6 +579,11 @@ impl SwatchChoices { Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), } } + /// Add for every conflict: each pasted swatch whose name the document gives another color + /// comes in renamed. + pub(crate) fn add_all() -> Self { + Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } + } fn of(&self, name: &str) -> SwatchChoice { self.by_name.get(name).copied().unwrap_or(self.all) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index a529a3bea9..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 ), @@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof } /// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the -/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps +/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings +/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps /// ([`map_graph_colors`]) and the art of every opacity mask. fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { map_effect_colors(&mut n.appearance, f); + map_stroke_brush_keys(&mut n.appearance, f); if let Some(e) = n.extras_if_any() { if let Some(g) = e.graph.as_deref_mut() { map_graph_colors(g, f); @@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo } } +/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a` +/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key +/// that does not read is left as it is. +/// +/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options +fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + for it in &mut a.items { + let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue }; + let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue }; + let Some(key) = c.get("key").and_then(|k| serde_json::from_value::(k.clone()).ok()) else { continue }; + let n = f(&key, None); + if n != key { + c.insert("key".into(), json!(n)); + } + } +} + /// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's /// colorization matches it with. fn matches_key(c: &Color, key: &Color) -> bool { @@ -1036,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/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index c7421ac391..0456a09321 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S (entry, (name, format!("{}, {detail}", kind.label()))) } +/// The artboards the Artboard tool has selected while it is the current tool, in artboard order, +/// with the index of its active artboard; none with another tool or when it has none of the +/// document's artboards selected. Indices the document does not have are left out. +fn artboard_tool_selection(s: &Session) -> Option<(Vec, usize)> { + if s.tool_id() != "artboard" { + return None; + } + let n = s.active().map_or(0, |d| d.doc.artboards.len()); + let t = s.tool_options_of("artboard"); + let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n); + let mut picked: Vec = t["selected"].as_array().into_iter().flatten().filter_map(index).collect(); + picked.sort_unstable(); + picked.dedup(); + let first = *picked.first()?; + let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first); + Some((picked, active)) +} + +/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the +/// current tool: their `selectedArtboards` entries (in the document's units), and for each its +/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of +/// artboard `active`. +fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec, Vec<(String, String)>) { + let (u, per) = (d.units, d.units.points()); + let origin = d.ruler_origin_for(active); + let mut entries = vec![]; + let mut rows = vec![]; + for &i in picked { + let Some(a) = d.artboards.get(i) else { continue }; + let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y); + entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per })); + rows.extend([ + ("Artboard".to_string(), a.name.clone()), + ("Width".into(), u.format(w)), + ("Height".into(), u.format(h)), + ("X".into(), u.format(x)), + ("Y".into(), u.format(y)), + ]); + } + (entries, rows) +} + /// The Document Info categories of `d` (only `category` when given) from `info` (what -/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of -/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or -/// stroked with a spot color, with a pattern and with a gradient. +/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts +/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows +/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a +/// pattern and with a gradient. #[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, + selected_artboards: &[(String, String)], fonts: &BTreeSet, font_details: &[(String, String)], images: &[ImageRow], @@ -215,7 +259,19 @@ fn sections( rows.extend( d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))), ); + rows.extend(selected_artboards.iter().cloned()); rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi))); + let setup = &d.setup; + let colors = match setup.grid_colors_name() { + "Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "), + name => name.to_string(), + }; + rows.extend([ + ("Grid Size".to_string(), setup.grid_size.label().to_string()), + ("Grid Colors".into(), colors), + ("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()), + ("Flattener Preset".into(), setup.flattener().to_string()), + ]); let counts = [ ("Swatches", "swatches"), ("Character Styles", "characterStyles"), @@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result { Some("text") => true, Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))), }; + let artboard_tool = artboard_tool_selection(s); let st = s.doc()?; let d = &st.doc; let selection_only = bool_or(p, "selectionOnly", false); @@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result { }); // The document's name: its file's, else its title. out["document"]["name"] = json!(st.title()); - let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category); + let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default(); + out["document"]["selectedArtboards"] = json!(selected_entries); + let sections = sections( + d, + &out, + &selected_rows, + &fonts, + &font_rows, + &image_rows, + &brush_rows, + &repeat_rows, + &spot_rows, + &pattern_rows, + &gradient_rows, + category, + ); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value { "unitId": d.units.key(), "artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::>(), "rasterEffectsPpi": d.raster_effects_ppi, + "transparency": { + "gridSize": d.setup.grid_size.id(), + "gridColors": d.setup.grid_colors.map(|c| c.to_hex()), + "gridColorsName": d.setup.grid_colors_name(), + "simulatePaper": d.setup.simulate_paper, + "flattenerPreset": d.setup.flattener(), + }, }) } @@ -875,6 +954,101 @@ mod tests { assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1); } + /// The Document category's rows from `info`, as (label, value) pairs. + fn document_rows(i: &Value) -> Vec<(String, String)> { + let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap(); + doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect() + } + + /// Document lists File › Document Setup's transparency settings: the grid's size and colors + /// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset. + #[test] + fn info_lists_the_transparency_settings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + let t = &i["document"]["transparency"]; + assert_eq!( + (t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()), + (json!("medium"), json!("Light"), json!(false), json!("Medium Resolution")) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap(); + let expected = + [("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + s.execute( + "document.setup", + &json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}), + ) + .unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"])); + assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom"); + let rows = document_rows(&i); + let expected = + [("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}"); + } + + /// While the Artboard tool is the current tool, Document lists each artboard it has selected + /// after the artboards: its name, width, height and the X and Y of its top-left corner from the + /// ruler origin of the tool's active artboard. With another tool it lists none. + #[test] + fn info_lists_the_artboards_the_artboard_tool_selected() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap(); + let before = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(before["document"]["selectedArtboards"], json!([])); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([2, 1, 7])); + let i = s.execute("document.info", &json!({})).unwrap(); + // Artboard 2 is active: positions are measured from its top-left corner. + assert_eq!( + i["document"]["selectedArtboards"], + json!([ + {"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0}, + {"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0}, + ]) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4; + let expected = [ + ("Artboard", "Artboard 2"), + ("Width", "60 pt"), + ("Height", "80 pt"), + ("X", "-250 pt"), + ("Y", "30 pt"), + ("Artboard", "Back"), + ("Width", "100 pt"), + ("Height", "50 pt"), + ("X", "0 pt"), + ("Y", "0 pt"), + ("Raster Effects", "72 ppi"), + ]; + assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + // The rows follow the document's units and its ruler origin. + s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap(); + s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap(); + s.set_tool_option("selected", &json!([2])); + let i = s.execute("document.info", &json!({"category": "document"})).unwrap(); + let entry = &i["document"]["selectedArtboards"]; + assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2))); + assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}"); + let rows = document_rows(&i); + assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}"); + // Another tool: no artboard rows. + s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["selectedArtboards"], json!([])); + assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i)); + } + /// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a /// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's. #[test] 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 05dae578ce..45171f62a1 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,wheel]…] (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. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven 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]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise, finger wheel 0..1; 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\" | \"stylusWheel\" (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; stylusWheel from less at one end of an airbrush pen's finger wheel travel to more at the other. 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 ), @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Path Eraser", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes", has_selection, erase_segments ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index bf52f580e7..36280196b7 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -22,15 +22,17 @@ pub(super) struct Sample { tilt: Option<[f64; 2]>, /// Barrel rotation, degrees clockwise. rotation: Option, + /// The airbrush finger wheel, 0..1. + wheel: Option, } /// The keys of a point's pen values, in the order a point given as an array holds them after its /// x and y. -const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"]; +const PEN_KEYS: [&str; 5] = ["pressure", "tiltX", "tiltY", "rotation", "wheel"]; -/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation -/// 0..360 degrees (360 is the same direction as 0). -const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)]; +/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees, rotation +/// 0..360 degrees (360 is the same direction as 0) and the wheel 0..1. +const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0), (0.0, 1.0)]; /// Blob Brush and Eraser Tool Options' Size, in points. pub(super) const SIZES: (f64, f64) = (0.1, 1000.0); @@ -61,11 +63,11 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { } /// [`points_param`] with what a pen read at each point, as far as it is given: -/// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure -/// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in -/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or -/// rotation is neither a number nor null or is outside its range, or an array of more than six -/// numbers, is an error. +/// `[[x,y,pressure,tiltX,tiltY,rotation,wheel]…]` or `[{x,y,pressure,tiltX,tiltY,rotation,wheel}…]`. +/// Pressure is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); +/// rotation in degrees clockwise, 0..360; the wheel 0..1. A point whose x or y is not a number, +/// whose pressure, tilt, rotation or wheel is neither a number nor null or is outside its range, +/// or an array of more than seven numbers, is an error. pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result> { let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?; let pts: Vec = a @@ -79,7 +81,7 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result xy.get(i + 2), @@ -91,9 +93,9 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))), }; } - let [pressure, tx, ty, rotation] = pen; + let [pressure, tx, ty, rotation, wheel] = pen; let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0))); - Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation }) + Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation, wheel }) }) .collect::>()?; if pts.is_empty() { @@ -126,6 +128,15 @@ fn stroke_pressure(samples: &[Sample]) -> Option { PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.pressure.unwrap_or(1.0)))) } +/// Where an airbrush pen's finger wheel was set along a freehand stroke, when any of its samples +/// has it; samples without it count as the middle of its travel, which draws a brush's own value. +fn stroke_wheel(samples: &[Sample]) -> Option { + if samples.iter().all(|s| s.wheel.is_none()) { + return None; + } + PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.wheel.unwrap_or(PressureProfile::MID)))) +} + /// A pen that leans less than this many degrees from upright leans no way in particular: its /// bearing is the one before it. const UPRIGHT: f64 = 1.0; @@ -165,24 +176,31 @@ fn stroke_pose(samples: &[Sample]) -> (Option, Option, tilt: Option, bearing: Option, rotation: Option, + wheel: Option, } impl PenRecord { /// What a freehand stroke's samples recorded. pub(super) fn of_samples(samples: &[Sample]) -> Self { let (tilt, bearing, rotation) = stroke_pose(samples); - Self { pressure: stroke_pressure(samples), tilt, bearing, rotation } + Self { pressure: stroke_pressure(samples), tilt, bearing, rotation, wheel: stroke_wheel(samples) } } pub(super) fn of(st: &StrokeLayer) -> Self { - Self { pressure: st.pressure.clone(), tilt: st.tilt.clone(), bearing: st.bearing.clone(), rotation: st.rotation.clone() } + Self { + pressure: st.pressure.clone(), + tilt: st.tilt.clone(), + bearing: st.bearing.clone(), + rotation: st.rotation.clone(), + wheel: st.wheel.clone(), + } } pub(super) fn is_empty(&self) -> bool { *self == Self::default() @@ -195,6 +213,7 @@ impl PenRecord { tilt: PressureProfile::extended(self.tilt.as_ref(), old_len, added.tilt.as_ref(), added_len), bearing: AngleProfile::extended(self.bearing.as_ref(), old_len, added.bearing.as_ref(), added_len), rotation: AngleProfile::extended(self.rotation.as_ref(), old_len, added.rotation.as_ref(), added_len), + wheel: PressureProfile::extended(self.wheel.as_ref(), old_len, added.wheel.as_ref(), added_len), } } /// The record along the path reversed. @@ -204,6 +223,7 @@ impl PenRecord { tilt: self.tilt.as_ref().map(PressureProfile::reversed), bearing: self.bearing.as_ref().map(AngleProfile::reversed), rotation: self.rotation.as_ref().map(AngleProfile::reversed), + wheel: self.wheel.as_ref().map(PressureProfile::reversed), } } /// Keep the record on stroke `st`. @@ -212,6 +232,7 @@ impl PenRecord { st.tilt = self.tilt; st.bearing = self.bearing; st.rotation = self.rotation; + st.wheel = self.wheel; } } @@ -345,18 +366,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 40a4c74d79..cc543f3e05 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; } @@ -407,7 +438,7 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result { /// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and /// `sizeMode`. -const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\""; +const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\", \"rotation\" or \"stylusWheel\""; /// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with /// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation` @@ -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()); @@ -522,13 +580,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) Ok(ids_json(&ids)) } +/// The Path Eraser's band width, in points (VectorCraft's own range). +const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0); + pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseSegments"; let pts = points_param(p, "points", C)?; - let w = number_or(p, "width", 8.0, C)?; - if !(w.is_finite() && w > 0.0) { - return Err(bad(C, "width must be positive")); - } + let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?; let st = s.doc()?; let mut plan = vec![]; for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) { diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 241d252816..607abf8f03 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError { bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke")) } -/// Sets brush `name` on the stroke of object `id` of `d`. +/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another +/// brush (Options of Selected Object) are cleared. fn set_brush(d: &mut Document, id: NodeId, name: &str) { if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + if st.brush.as_deref() != Some(name) { + st.brush_options.clear(); + } st.brush = Some(name.to_string()); } } @@ -209,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, @@ -234,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"))?; @@ -276,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 a17a02ed15..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)); @@ -1150,21 +1154,27 @@ fn random_brushes_baked<'a>( std::borrow::Cow::Owned(def) } -/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or -/// scatter brush with Random variation, or a bristle brush? -fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool { +/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different +/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle +/// brush? +fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map) -> bool { use vectorcraft_brush::{BrushKind, Variation}; - brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind { + let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false }; + let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() }; + let b = edited.as_ref().unwrap_or(brush); + match &b.kind { BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random), BrushKind::Scatter(s) => s.modes().contains(&Variation::Random), BrushKind::Bristle(_) => true, BrushKind::Art(_) | BrushKind::Pattern(_) => false, - }) + } } /// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])? fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool { - let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b)); + let random = |st: &vectorcraft_doc::appearance::StrokeLayer| { + st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options)) + }; matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st))) } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index a6e913f9f6..f9031f3204 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -41,7 +41,7 @@ mod load; mod mesh3d; pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note}; mod heifread; -mod hpgl; +pub mod hpgl; mod jp2read; mod metafile; mod naming; @@ -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; @@ -133,7 +134,7 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; -pub(crate) use access::{check_images_in, check_scripts_of}; +pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 9d2d9a4a33..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() @@ -171,13 +173,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards } } -/// The error for an SVG that would name a linked image's file outside the read roots. +/// The error for a file that would name a linked image's file outside the read roots. pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots"; /// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it -/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and -/// those too unless read roots are in force and the file would name a linked image's file outside -/// them (a relative path taken from `st`'s folder; a URL is not checked). An `` names the +/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in +/// force and the file would name a linked image's file outside them (a relative path taken from +/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it +/// carries the native document ([`check_native_images`]). An `` names the /// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for /// the image, for the images of the art each file draws (with chosen artboards, the art over each /// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask @@ -193,9 +196,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve /// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the /// objects on the clipboard, looked for from the document they came from). pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> { - if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() { + if crate::file_access::current().is_none() { return Ok(()); } + if !matches!(format, "svg" | "svgz") { + return check_native_images(cmd, format, d, base, p); + } // Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden // layers kept and SVG 1.1: the encoder refuses them anyway. let (link, preserve, hidden, tiny) = match super::svg::options_map(p) { @@ -222,6 +228,39 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu Ok(()) } +/// `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, 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 +/// read). The error names no file or folder. +pub(crate) fn check_native_images( + cmd: &str, + format: &str, + d: &vectorcraft_doc::Document, + base: crate::cmd::links::LinkBase, + p: &Value, +) -> Result<()> { + let carried = + crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len()); + if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) } +} + +/// `doc` as a file written for the request being served carries it: without an Export for Screens +/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The +/// open document keeps it. +pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> { + let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); + if settings.len() == doc.export_settings.len() { + return std::borrow::Cow::Borrowed(doc); + } + let mut kept = doc.clone(); + kept.export_settings = settings; + std::borrow::Cow::Owned(kept) +} + /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn may_write(path: &str) -> Result<()> { @@ -258,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). @@ -266,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 @@ -285,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..1ecb41290e 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -878,7 +878,7 @@ fn without_nodes(n: &Arc, left_out: &dyn Fn(&Node) -> bool, changed: Optio /// absent; an error when it is not four finite numbers with a positive size, when the format isn't /// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would /// contradict it). The image size limits are checked with the scale, as for an artboard. -fn page_rect(f: &Format, p: &Value) -> Result> { +pub(super) fn page_rect(f: &Format, p: &Value) -> Result> { let v = match p.get("rect") { None | Some(Value::Null) => return Ok(None), Some(v) => v, @@ -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/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index 3acd23e854..5067b1c6d5 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result { } /// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of -/// several artboards), with linked images whole when `include_linked`. +/// several artboards), with linked images whole when `include_linked`, and without an Export for +/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]). fn native(doc: &Document, board: Option, include_linked: bool) -> Vec { + let doc = &*super::access::with_readable_settings_folder(doc); let several = board.filter(|_| doc.artboards.len() > 1); if several.is_none() && !include_linked { return vectorcraft_format::save(doc, false); diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index c53822868c..2cc57144fb 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator impl Iterator { - std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts))) + std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label)) } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, diff --git a/crates/engine/src/cmd/fileio/hpgl.rs b/crates/engine/src/cmd/fileio/hpgl.rs index 1baac844e6..bf98457771 100644 --- a/crates/engine/src/cmd/fileio/hpgl.rs +++ b/crates/engine/src/cmd/fileio/hpgl.rs @@ -6,6 +6,7 @@ use serde_json::Value; use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; use vectorcraft_cad::hpgl::{HpglOptions, Origin, Version}; use vectorcraft_doc::Document; +use vectorcraft_geom::Rect; use super::super::{Result, bad, number_or, switch_or, text_param}; use super::{ArtboardPick, Encoded, FormatOption}; @@ -92,10 +93,58 @@ fn hex(v: &Value) -> Option<[u8; 3]> { Some([byte(0)?, byte(2)?, byte(4)?]) } -/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with -/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all. -pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> Result { - let opts = parse(p)?; +/// Check the HP-GL options and the artboard choice in `p` for an export of `doc`, as the export +/// reads them, without exporting (dialogs keep themselves open on an error). +pub fn check(doc: &Document, p: &Value) -> std::result::Result<(), String> { + let run = || -> Result<()> { + parse(p)?; + with_plotted(doc, p, |_, _| Ok(())) + }; + run().map_err(|e| e.to_string()) +} + +/// The pen table an export of `doc` with the options and artboard choice in `p`, and no `pens`, +/// uses: pen 1's color first, as `#rrggbb` colors. Empty when nothing is plotted; an error when +/// the options or the artboard choice are refused. +pub fn automatic_pens(doc: &Document, p: &Value) -> std::result::Result, String> { + let run = || -> Result> { + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.remove("pens"); + } + // The order the paths are drawn in doesn't change which pen a color gets. + let opts = HpglOptions { sort: false, inside_first: false, ..parse(&q)? }; + with_plotted(doc, &q, |doc, regions| { + let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?; + Ok(plots.first().map(|o| o.pens.clone()).unwrap_or_default()) + }) + }; + let pens = run().map_err(|e| e.to_string())?; + Ok(pens.iter().map(|[r, g, b]| format!("#{r:02x}{g:02x}{b:02x}")).collect()) +} + +/// Run `f` on the document an export of `doc` with `p` plots and the regions of its plots: with +/// `useArtboards: false`, a copy of `doc` whose one artboard is the bounds of the visible art. +/// Like the export, it refuses `rect`, leaves out an opacity-mask or symbol editing layer, and +/// measures the bounds without the art a plot draws nothing for. +fn with_plotted(doc: &Document, p: &Value, f: impl FnOnce(&Document, Vec) -> Result) -> Result { + let format = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?; + super::encode::page_rect(format, p)?; + let doc = &*doc.without_edit_modes(); + let use_artboards = super::encode::use_artboards(C, p)?; + if use_artboards == Some(false) + && let Some((art, q)) = super::encode::art_page(C, doc, p, |n| vectorcraft_cad::hpgl::write::plots_nothing(doc, n))? + { + let (_, regions) = boards(&art, &q, None)?; + return f(&art, regions); + } + let (_, regions) = boards(doc, p, use_artboards)?; + f(doc, regions) +} + +/// The artboards a plot of `doc` covers and their regions: the chosen artboard (default the +/// first), or with `use_artboards` each chosen one (default all). +fn boards(doc: &Document, p: &Value, use_artboards: Option) -> Result<(Vec, Vec)> { let f = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?; let pick: ArtboardPick = super::encode::options(f, p)?; let n = doc.artboards.len(); @@ -103,10 +152,25 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> 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 regions = boards .iter() .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) .collect::>>()?; + // The writer's own region check, so a dialog's check refuses what the writer refuses. + for r in ®ions { + vectorcraft_cad::hpgl::write::check_region(*r).map_err(|e| bad(C, e))?; + } + Ok((boards, regions)) +} + +/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with +/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all. +pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> Result { + let opts = parse(p)?; + let (boards, regions) = boards(doc, p, use_artboards)?; let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); for (b, out) in boards.into_iter().zip(plots) { @@ -118,9 +182,6 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> } enc.add_setting_notes(out.setting_notes); } - if enc.files.is_empty() { - return Err(bad(C, "the document has no artboard")); - } let regions: Vec = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect(); enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions))); Ok(enc) 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/native.rs b/crates/engine/src/cmd/fileio/native.rs index cbf46c97c0..a4e0e4d24c 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } other => other, }; + // Without an Export for Screens folder outside the read roots. + let native = super::access::with_readable_settings_folder(&native); so.pretty = so.pretty_fits(&native); vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string())) } @@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result 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"; @@ -338,7 +525,9 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option = placed.into_iter().map(Note::loss).collect(); - let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; + // 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, 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)) { @@ -362,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))?; @@ -399,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()?); @@ -504,6 +702,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { let p = &*expanded; let st = s.doc()?; super::check_linked_scripts(C, "pdf", st, p)?; + super::check_linked_images(C, "pdf", st, &st.doc, p)?; let display_doc_title = super::has_own_title(&st.doc); let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf"); let mut q = p.clone(); 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 0afcd9c941..f03dc6fe0d 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> { @@ -896,7 +914,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option std::borrow::Cow::Borrowed(¶ms), }; super::check_linked_scripts(cmd, plan.format.id, st, &checked)?; + super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?; Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards }) } @@ -1022,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)?; @@ -1042,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); @@ -1066,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 { @@ -1087,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 b8e797373d..442f38e3cc 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool { super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len()) } +/// The document the file of `item` that row `r` writes carries when it carries one +/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a +/// native, `.ai` or EPS row ([`board_document`]), else the item's document. +fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> { + match (&item.every_artboard, r.format.id, single) { + (Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all), + _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)), + _ => std::borrow::Cow::Borrowed(&*item.doc), + } +} + +/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with +/// its background color and the art on it, as Save's separateArtboards writes it (#3868). +fn board_document(item: &Item) -> Document { + let mut d = single_artboard(&item.doc, item.region, &item.name); + if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) { + a.color = from.color; + } + super::save::keep_art_on(&mut d, item.region); + d +} + /// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and @@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?; } } + // The native document the files of the other rows carry, each document looked through once. + if crate::file_access::current().is_some() { + let mut looked: HashSet<(usize, bool, Option)> = HashSet::new(); + for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) { + // A single-file PDF carries the first item's document alone, as the writer writes it. + let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0)); + for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) { + let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none(); + let board = item.artboard.filter(|_| !all && r.whole_document()); + if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board)) + && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base) + { + return Err(bad(C, super::access::IMAGE_OUTSIDE)); + } + } + } + } // Appearance of Black › Printing / Exporting for RGB raster rows. // Include Artboard Fill off: the encoders leave the background colors out. let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) }; @@ -1310,16 +1349,21 @@ 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) }; - // A whole-document copy of an artboard, for the formats that write documents to edit. - let mut board_docs: std::collections::HashMap> = std::collections::HashMap::new(); + // A whole-document copy of an artboard of an item's document, for the formats that write + // documents to edit. + let mut board_docs: std::collections::HashMap<(usize, usize), Arc> = std::collections::HashMap::new(); let mut files = 0u64; // One step per item and row, the files a name collision skips included. let steps = (items.len() * rows.len()) as u64; @@ -1358,19 +1402,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> write(pdf_doc.unwrap_or(all), "pdf", &options)? } else if r.whole_document() && item.artboard.is_some() { let b = item.artboard.unwrap_or(0); - // That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868). - let d = board_docs - .entry(b) - .or_insert_with(|| { - let mut d = single_artboard(&item.doc, item.region, &item.name); - // It keeps its background color. - if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) { - a.color = from.color; - } - super::save::keep_art_on(&mut d, item.region); - Arc::new(d) - }) - .clone(); + let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone(); let mut options = r.options_for(item.region, None)?; // An EPS page is the artboard, not its art's bounds: an artboard without art still writes. if r.format.id == "eps" { diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index bcc01e37a4..066c6fc63f 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> /// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` /// outside the read roots of the request being served (the open document keeps it). fn native_attachment(doc: &Document) -> Vec { - let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); - if settings.len() == doc.export_settings.len() { - return vectorcraft_format::save(doc, false); - } - let mut kept = doc.clone(); - kept.export_settings = settings; - vectorcraft_format::save(&kept, false) + vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false) } /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index bbf6883834..56e2a12f30 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() { } } +/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load +/// as a library, and it is the only filter of that label. +#[test] +fn the_swatch_library_filter_lists_ai_and_eps_files() { + let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect(); + for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] { + assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]); + } + assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}"); + // File › Open still opens a `.ai` as a document, not as a swatch library. + assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai")); +} + /// The extensions usage texts list for export: one per writable format, each picking that format /// (`.png` picks PNG; PNG-8 is asked for by `format`). #[test] @@ -922,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_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 9d263c8c97..3754752939 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the +/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with +/// `square` (a color operator), a color the palette doesn't list. +fn textures_library(square: &str) -> Vec { + let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"); + let gradient = + "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\ + 1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n"; + let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}")); + ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f") +} + +/// `swatch.library.load` of `file` named `name` → its library id. +fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value { + let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name}); + s.execute("swatch.library.load", &p).unwrap()["library"].clone() +} + +/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its +/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's +/// tile and art in the document, in the library's color group, not the pattern's colors. +#[test] +fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let kinds: Vec<(&str, &str, Option<&str>)> = + lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect(); + assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}"); + assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}"); + // The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own. + let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap(); + let tiles = library.iter().find(|w| w.name == "Tiles").unwrap(); + assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some())); + assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none()); + + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap(); + assert_eq!(r["added"], json!(["Tiles"]), "{r}"); + let doc = &s.doc().unwrap().doc; + let dots = doc.pattern("Dots").expect("the pattern comes with its swatch"); + assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0)); + assert_eq!(dots.art.len(), 1, "{:?}", dots.art); + let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too"); + let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect(); + assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}"); + // Added again, the swatch the document has is used. + let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}"); +} + +/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list +/// still comes in with that color in its art. +#[test] +fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + let doc = &s.doc().unwrap().doc; + let art = &doc.pattern("Dots").unwrap().art; + let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color()); + assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}"); + // Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is + // refused, writes nothing and leaves the library loaded. + let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id())); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string(); + assert!(e.contains("`textures` has pattern swatches"), "{e}"); + assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written"); + assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as +/// swatch libraries with a message, not listed as the default swatches or as an empty library. A +/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file +/// with no swatches loads as an empty library. +#[test] +fn swatch_library_documents_without_swatches_or_damaged_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.edit("Clear", |d, _| { + d.swatches.clear(); + d.swatch_groups.clear(); + Ok(()) + }) + .unwrap(); + let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string(); + assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}"); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)))); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("`art.ai` has no swatches of its own"), "{e}"); + let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"}); + assert!(s.execute("swatch.library.load", &damaged).is_err()); + let list = s.execute("swatch.library.list", &json!({})).unwrap(); + assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}"); + // A library file without swatches still loads, as an empty library. + let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap(); + assert_eq!(r["count"], json!(0), "{r}"); +} + /// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the /// library the styles of its list, in the list's order, not the default styles; the file opens with /// them too. 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_hpgl.rs b/crates/engine/src/cmd/fileio/tests_hpgl.rs index 8714072257..9a74b8513b 100644 --- a/crates/engine/src/cmd/fileio/tests_hpgl.rs +++ b/crates/engine/src/cmd/fileio/tests_hpgl.rs @@ -534,6 +534,104 @@ fn export_options_are_checked() { let p = json!({"format": "hpgl", "origin": "CENTER", "pens": ["#ff0000", "#000000"], "curveTolerance": 10, "sortPaths": true}); let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap(); assert_eq!(plot, "IN;PU;SP2;PU-141,141;PD-564,141,-564,564,-141,564,-141,141;PU;SP0;"); + // The check a dialog runs refuses the same options, and passes the given ones. + let doc = s.doc().unwrap().doc.clone(); + assert!(hpgl::check(&doc, &json!({"pens": ["#ff0000", "red"]})).unwrap_err().contains("`pens`")); + assert!(hpgl::check(&doc, &json!({"curveTolerance": 11})).unwrap_err().contains("`curveTolerance`")); + assert_eq!(hpgl::check(&doc, &p), Ok(())); + // It checks the artboard choice as the export does: an artboard or range past the document's, + // a `useArtboards` that isn't true or false, and the art's bounds when no art shows. + let mut blank = Session::new(); + blank.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let blank_doc = blank.doc().unwrap().doc.clone(); + for (on_blank, p) in [ + (false, json!({"format": "hpgl", "artboard": 2})), + (false, json!({"format": "hpgl", "useArtboards": true, "range": "1-3"})), + (false, json!({"format": "hpgl", "artboards": [0, 1]})), + (false, json!({"format": "hpgl", "useArtboards": "yes"})), + (true, json!({"format": "hpgl", "useArtboards": false})), + ] { + let (session, d) = if on_blank { (&mut blank, &blank_doc) } else { (&mut s, &doc) }; + assert!(hpgl::check(d, &p).is_err(), "{p}"); + assert!(session.execute("document.export", &p).is_err(), "{p}"); + } + // An artboard with no width is refused before the writer refuses it. + let mut flat = vectorcraft_doc::Document::clone(&doc); + flat.artboards[1].rect = vectorcraft_geom::Rect::new(200.0, 0.0, 200.0, 100.0); + assert_eq!(hpgl::check(&flat, &json!({"artboard": 1})).unwrap_err(), hpgl::check(&flat, &json!({"useArtboards": true})).unwrap_err()); + assert!(hpgl::check(&flat, &json!({"artboard": 1})).unwrap_err().contains("the export region is empty")); + assert_eq!(hpgl::check(&flat, &json!({})), Ok(())); + // A document with no artboard has nothing to plot on one, or on each. + flat.artboards.clear(); + for p in [json!({}), json!({"useArtboards": true})] { + assert!(hpgl::check(&flat, &p).unwrap_err().contains("the document has no artboard"), "{p}"); + } + // An area of the page is a raster export's option: the export refuses it, and so does the check. + let rect = json!({"format": "hpgl", "rect": [0, 0, 10, 10]}); + assert!(s.execute("document.export", &rect).is_err()); + assert!(hpgl::check(&doc, &rect).unwrap_err().contains("rect applies to raster formats")); + assert_eq!(hpgl::check(&doc, &json!({"useArtboards": true, "range": "2"})), Ok(())); + assert_eq!(hpgl::check(&doc, &json!({"useArtboards": false})), Ok(())); +} + +/// The pens an export without a pen table uses: one per color the plotted art draws in, in the +/// order it first draws in each, over the artboards or the art's bounds the export plots. +#[test] +fn automatic_pens_list_the_plotted_art_s_colors_in_pen_order() { + let s = two_boards(); + let doc = &s.doc().unwrap().doc; + let pens = |p: Value| hpgl::automatic_pens(doc, &p).unwrap(); + assert_eq!(pens(json!({})), ["#000000"], "the first artboard"); + assert_eq!(pens(json!({"artboard": 1})), ["#ff0000"]); + assert_eq!(pens(json!({"useArtboards": true})), ["#000000", "#ff0000"], "one numbering for every file"); + assert_eq!(pens(json!({"useArtboards": false})), ["#000000", "#ff0000"], "the art's bounds"); + // The pens given and the path order are not the export's own pens. + assert_eq!(pens(json!({"useArtboards": true, "pens": ["#00ff00"], "sortPaths": true})), ["#000000", "#ff0000"]); + // A refused artboard choice or option is an error, not an empty table. + assert!(hpgl::automatic_pens(doc, &json!({"artboard": 5})).is_err()); + assert!(hpgl::automatic_pens(doc, &json!({"curveTolerance": 20})).unwrap_err().contains("`curveTolerance`")); + // So is an area of the page, which the export and the check refuse for HP-GL. + assert!(hpgl::automatic_pens(doc, &json!({"rect": [0, 0, 10, 10]})).unwrap_err().contains("rect applies to raster formats")); + + // Art outside every artboard is plotted only with the art's bounds. + let mut off = Session::new(); + off.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + off.execute("paint.setFill", &json!({"none": true})).unwrap(); + off.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + off.execute("shape.rectangle", &json!({"x": 500, "y": 500, "width": 30, "height": 30})).unwrap(); + let doc = &off.doc().unwrap().doc; + assert_eq!(hpgl::automatic_pens(doc, &json!({})), Ok(vec![])); + assert_eq!(hpgl::automatic_pens(doc, &json!({"useArtboards": false})), Ok(vec!["#0000ff".to_string()])); +} + +/// A placed document opened with only its preview is plotted with its file's art (the plot reads +/// the file), so the check and the pens of a dialog measure that art as the export does. +#[test] +fn a_placed_document_s_pens_are_those_of_its_file_s_art() { + use crate::tests_links::{Folder, open, save, session, write}; + let dir = Folder::new("hpgl-placed"); + let src = dir.file("logo.vectorcraft"); + let mut d = vectorcraft_doc::Document::new(100.0, 50.0); + let layer = d.layers[0].id; + let id = d.alloc_id(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0)); + let look = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0); + let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 50.0)); + d.insert(Some(layer), 0, vectorcraft_doc::Node::path(id, rect, look)).unwrap(); + write(&src, &vectorcraft_format::save_file(&d)); + let mut s = session(); + s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap(); + let poster = dir.file("poster.vectorcraft"); + save(&mut s, &poster); + open(&mut s, &poster); + let doc = &s.doc().unwrap().doc; + assert!(doc.images.values().any(vectorcraft_doc::ImageBlob::is_proxy), "opened with the preview only"); + for p in [json!({}), json!({"useArtboards": false})] { + assert_eq!(hpgl::automatic_pens(doc, &p), Ok(vec!["#ff0000".to_string()]), "{p}"); + assert_eq!(hpgl::check(doc, &p), Ok(()), "{p}"); + } + let plot = String::from_utf8(bytes(&s.execute("document.export", &json!({"format": "hpgl"})).unwrap())).unwrap(); + assert!(plot.contains("SP1;") && plot.contains("PD"), "{plot}"); } /// `insideFirst` draws the square inside the other one first, though it was made last. 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 0f610b073f..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]> { @@ -1461,3 +1490,25 @@ fn an_export_preset_adds_no_notes() { let r = export(&mut s, json!({"exportPreset": "Mixed"})); assert!(unused(&r).is_empty(), "{r}"); } + +/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art: +/// every piece's file holds its own artboard, named after it, not the first piece's. +#[test] +fn each_piece_writes_its_own_native_document() { + let mut s = session(1); + s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + let mut assets = vec![]; + for (id, name) in ids.iter().zip(["Square", "Circle"]) { + assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap()); + } + let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]})); + let written = files(&r); + assert_eq!(written.len(), 4, "{r}"); + for (name, bytes) in written { + let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes }; + let doc = vectorcraft_format::load(&native).unwrap(); + let board = doc.artboards[0].name.clone(); + assert!(name.contains(&board), "{name} holds the artboard {board}"); + } +} diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index c7716940a1..7b5545ddca 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -437,3 +437,48 @@ fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() { assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 8), "at {x}: {a:?} vs {b:?}"); } } + +/// #864 / G11: SVG export preserves the document's physical units on the root `width`/`height` so +/// that the unit setting survives a save/open round-trip. The engine-level test covers the full +/// stack (file.new → document.setUnits → document.serialize → document.open). +#[test] +fn svg_round_trip_preserves_document_units() { + // (unit name the engine accepts, expected unit after re-import) + let cases: &[(&str, vectorcraft_doc::Unit)] = &[ + ("millimeters", vectorcraft_doc::Unit::Millimeters), + ("centimeters", vectorcraft_doc::Unit::Centimeters), + ("inches", vectorcraft_doc::Unit::Inches), + ("picas", vectorcraft_doc::Unit::Picas), + // Points and pixels both serialise as bare user-unit numbers, so both import as Pixels. + ("pixels", vectorcraft_doc::Unit::Pixels), + ]; + for (name, expected) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap(); + s.execute("document.setUnits", &json!({"units": name})).unwrap(); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg_text = r["text"].as_str().unwrap(); + match *expected { + vectorcraft_doc::Unit::Millimeters => assert!(svg_text.contains("mm\""), "mm suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Centimeters => assert!(svg_text.contains("cm\""), "cm suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Inches => assert!(svg_text.contains("in\""), "in suffix missing: {svg_text}"), + vectorcraft_doc::Unit::Picas => assert!(svg_text.contains("pc\""), "pc suffix missing: {svg_text}"), + _ => {} + } + let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes()); + s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap(); + let doc_state = s.doc().unwrap(); + assert_eq!(doc_state.doc.units, *expected, "unit mismatch after round-trip for '{name}'"); + } + + // Points serialise without suffix and re-open as Pixels (equivalent in user units). + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap(); + s.execute("document.setUnits", &json!({"units": "points"})).unwrap(); + let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg_text = r["text"].as_str().unwrap(); + assert!(svg_text.contains("width=\"200\" height=\"100\""), "{svg_text}"); + let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes()); + s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap(); + assert_eq!(s.doc().unwrap().doc.units, vectorcraft_doc::Unit::Pixels); +} 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/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 879767d8be..660df05f71 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -746,8 +746,8 @@ fn give_appearance(a: &Appearance, b: &Appearance, m: &Appearance, n: &mut Share } /// Give the member's fill or stroke `n` the settings of the model's that changed from `a` to `b`, -/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing and -/// rotation stay its own. +/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing, +/// rotation and wheel stay its own. fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut AppearanceItem) { use AppearanceItem::{Fill, Stroke}; match (a, b, m, n) { @@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut arrow_scale, profile, brush, + brush_options, opacity, blend, visible, @@ -780,8 +781,13 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut tilt: _, bearing: _, rotation: _, + wheel: _, } = m; - give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + // A stroke's own brush settings go with the brush they set: a new brush takes the model's. + if a.brush != b.brush { + n.brush_options = brush_options.clone(); + } } _ => {} } diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 301d361a1a..f1db9dd58a 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values}; #[cfg(test)] use columns::{fill_totals, total_text}; pub use commands::specs; -pub(crate) use data::{apply_csv, parse_csv}; +pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; pub use edit::{GraphTypeSubject, graph_type_subject}; diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 68a83fd80a..11cfd4ed26 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String { g.to_csv() } +// ---------- graph data files ---------- + +/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns +/// read, 1 MB (1,048,576 bytes). +pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20; + +/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels +/// before its series; a cell's longest text. +const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1; +const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1; +const SHEET_CELL: usize = 256; + +/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode +/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives +/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one. +/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired +/// surrogate reads as U+FFFD. +pub fn graph_data_text(bytes: &[u8]) -> String { + let utf16 = |rest: &[u8], le: bool| { + let units: Vec = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); + String::from_utf16_lossy(&units) + }; + match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, true), + [0xFE, 0xFF, rest @ ..] => utf16(rest, false), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + _ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() { + Some(le) => utf16(bytes, le), + None => String::from_utf8_lossy(bytes).into_owned(), + }, + } +} + +/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256 +/// characters. +pub fn graph_cell_text(s: &str) -> String { + s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect() +} + +/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds +/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file +/// stays whole), at most a graph's rows and columns. +pub fn graph_grid_from_text(text: &str) -> Vec> { + let sep = if text.contains('\t') { '\t' } else { ',' }; + text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect() +} + +/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the +/// first column the category labels (none when all are blank), and the other cells the values (a +/// blank cell, or text that isn't a number, has none), without the empty rows and columns past +/// the data. +pub fn graph_data_from_grid(grid: &[Vec]) -> Value { + let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default(); + let filled = |s: &String| !s.trim().is_empty(); + // At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by + // automation is any size, and the values are their product. + let grid = &grid[..grid.len().min(SHEET_ROWS)]; + let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1); + let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); + let label = |s: &str| { + let s = s.trim(); + // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. + s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() + }; + // Series labels up to the last one given (none when all are blank). + let mut series: Vec = (1..cols).map(|c| label(&cell(0, c))).collect(); + while series.last().is_some_and(String::is_empty) { + series.pop(); + } + let mut categories: Vec = (1..rows).map(|r| label(&cell(r, 0))).collect(); + if categories.iter().all(String::is_empty) { + categories.clear(); + } + let values: Vec> = (1..rows) + .map(|r| { + (1..cols) + .map(|c| { + let t = cell(r, c); + t.trim().parse::().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) + }) + .collect() + }) + .collect(); + json!({ "series": series, "categories": categories, "rows": values }) +} + +/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph +/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the +/// value gives a graph the data that Import Data and Apply give it. +pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result { + let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes))); + let mut spec = GraphSpec::default(); + apply_data(&mut spec, &data, "dataset.import")?; + Ok(spec.to_csv()) +} + /// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with /// `csv` does. Data the graph already holds leaves the graph as it is. pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { @@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result 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 { @@ -47,18 +68,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { }; let len = edit::runs_len(&t.runs); let from_tool = editing == Some(id); - let (a, b) = match p.get("at") { - None | Some(Value::Null) if from_tool => { - let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); - let (x, y) = (g("start"), g("end")); - (x.min(y), x.max(y)) - } - None | Some(Value::Null) => (len, len), - Some(v) => { - let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; - (at, at) - } + // Where the graphic goes in text `len` bytes long. + let range = |len: usize| -> Result<(usize, usize)> { + Ok(match p.get("at") { + None | Some(Value::Null) if from_tool => { + let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); + let (x, y) = (g("start"), g("end")); + (x.min(y), x.max(y)) + } + None | Some(Value::Null) => (len, len), + Some(v) => { + let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; + (at, at) + } + }) }; + let (mut a, mut b) = range(len)?; let symbol = match str_param(p, "symbol") { Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(), Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))), @@ -76,11 +101,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => 0.0, Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?, }; - // A typing session ends first: the insertion is a step of its own. + // A typing session ends first: the insertion is a step of its own. Typing that Real-time + // Drawing off left unapplied is applied first, and the caret is read in the typed text. let typing = tool.get("typing").and_then(Value::as_bool) == Some(true); if typing && from_tool { s.set_tool_option("commitTyping", &Value::Bool(true)); - s.commit_interaction()?; + super::settle_interaction(s)?; + let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else { + return Err(bad(C, format!("node {} is not text", id.0))); + }; + (a, b) = range(edit::runs_len(&t.runs))?; } let caret = s.edit("Insert Inline Symbol", |d, _| { let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) }; 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 81d1c72497..392d6340c6 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -36,7 +36,7 @@ use vectorcraft_doc::{ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?} 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)", + "{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)?; @@ -2686,11 +2687,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result, String craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } +/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't +/// name). +fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str { + fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")) +} + +/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is +/// stored in that format, else converted. +fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result, String> { + let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime); + if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) } +} + fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + // `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too. + super::params::check_exclusive_keys(C, p)?; + let ids = ids_param(p, "ids", C)?; + if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) { + return unembed_to_folder(s, p, ids); + } let st = s.doc()?; let doc = with_brush_art(&st.doc); - let id = image_param(st, &doc, p, C)?; + // `ids` of one image is `id`. + let id = match ids.as_deref() { + Some(&[id]) => id, + _ => image_param(st, &doc, p, C)?, + }; let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; if im.link.is_some() { @@ -2698,15 +2723,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result { } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. - let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")); + let stored = stored_extension(blob); let path = str_param(p, "path"); let ext = match path.map(fileio::extension) { Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e, Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))), _ => stored.to_string(), }; - let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime); - let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? }; + let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?; let Some(path) = path else { let name = n.display_name(); let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned()); @@ -2722,6 +2746,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "path": path })) } +/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the +/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of +/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it +/// are removed and the document does not change. +fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Result { + const C: &str = "links.unembed"; + let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?; + let ids = match ids { + Some(ids) => Some(ids), + None => object_param(p, "id", C)?.map(|id| vec![id]), + }; + let st = s.doc()?; + let doc = with_brush_art(&st.doc); + let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none())); + let mut seen = BTreeSet::new(); + if !ids.iter().all(|id| seen.insert(id.0)) { + return Err(bad(C, "`ids` names an object twice")); + } + let (mut embedded, mut skipped) = (vec![], vec![]); + for &id in &ids { + let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; + let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; + if im.link.is_some() { + skipped.push(id); + continue; + } + let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; + embedded.push((id, n.display_name(), blob)); + } + match (embedded.is_empty(), skipped.first()) { + (true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))), + (true, None) => return Err(bad(C, "select an image")), + _ => {} + } + let dir = absolute_path(folder); + writable_folder(&dir)?; + // One image at a time: its bytes are read before its file is written, so pixels that can't be + // read leave no file behind. + let mut written: Vec = vec![]; + let mut reads = Vec::with_capacity(embedded.len()); + let wrote = embedded.iter().try_for_each(|(id, name, blob)| { + vectorcraft_doc::cancel::check()?; + let ext = stored_extension(blob); + let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?; + let name = format!("{}.{ext}", unembed_stem(name)); + let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?; + let path = write_numbered(&dir, &name, &bytes)?; + written.push(path.clone()); + reads.push((*id, (link_info(&path, &bytes), img))); + Ok(()) + }); + let remove_written = |written: &[String]| { + for path in written { + let _ = std::fs::remove_file(path); + } + }; + if let Err(e) = wrote { + remove_written(&written); + return Err(e); + } + drop(doc); + let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); + let edited = s.edit("Unembed", |d, _| { + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None))) + }); + if let Err(e) = edited { + remove_written(&written); + return Err(e); + } + Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) })) +} + +/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without +/// a folder part or extension, each character a file name can't hold on some system +/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and +/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a +/// device (`CON`, `NUL`, `COM1` …) gets `_` after it. +fn unembed_stem(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or_default(); + let stem = match base.rfind('.') { + Some(i) if i > 0 => &base[..i], + _ => base, + }; + let mut clean = String::new(); + for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) { + if clean.len() + c.len_utf8() > 150 { + break; + } + clean.push(c); + } + let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']); + if clean.is_empty() { + return "Image".to_string(); + } + let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); + let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9'))); + if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") { + format!("{clean}_") + } else { + clean.to_string() + } +} + +/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder. +#[cfg(not(target_arch = "wasm32"))] +fn writable_folder(path: &str) -> Result<()> { + crate::file_access::check_write(path).map_err(EngineError::Other)?; + if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) { + return Err(EngineError::Other(format!("{path} is not a folder"))); + } + Ok(()) +} + +/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`, +/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path. +#[cfg(not(target_arch = "wasm32"))] +fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result { + use std::io::Write as _; + let create = |to: &Path| { + crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; + vectorcraft_format::write_new_with(to, |f| f.write_all(bytes)) + }; + match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) { + Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()), + Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))), + Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))), + } +} + +/// The web has no folders to write to. +#[cfg(target_arch = "wasm32")] +fn writable_folder(_: &str) -> Result<()> { + Err(EngineError::Other("no file system here".into())) +} + +#[cfg(target_arch = "wasm32")] +fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result { + Err(EngineError::Other("no file system here".into())) +} + /// Placement Options as `{preserve, align, clip}`. fn placement_json(o: PlacementOptions) -> Value { json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip }) @@ -2901,4 +3065,28 @@ mod tests { let c = read(); assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + + #[test] + fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { + for (name, stem) in [ + ("photo.png", "photo"), + ("Image", "Image"), + ("../../etc/passwd", "passwd"), + ("C:\\art\\logo.tif", "logo"), + ("a:b*c?d\"eg|h", "a_b_c_d_e_f_g_h"), + ("tab\there", "tab_here"), + (" name. .png", "name"), + ("..", "Image"), + ("", "Image"), + (".hidden", ".hidden"), + ("CON.png", "CON_"), + ("lpt1", "lpt1_"), + ("COM0", "COM0"), + ("console", "console"), + ] { + assert_eq!(unembed_stem(name), stem, "{name:?}"); + } + let long = unembed_stem(&"é".repeat(200)); + assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len()); + } } 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 2a073ab62a..a1464ebcef 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -1,6 +1,6 @@ //! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset -//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and -//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.) +//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, +//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.) use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::sync::Arc; @@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member, - has_selection, switch_or, + CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc, + has_selected_member, has_selection, switch_or, }; /// Session-level (not saved) state owned by the menu commands. @@ -110,6 +110,15 @@ pub fn specs() -> Vec { has_selection, reset_bounding_box ), + cmd!( + "object.rotateBoundingBox", + "Rotate Bounding Box…", + ["Object", "Transform"], + None, + "{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}", + has_selection, + rotate_bounding_box + ), cmd!( "object.rasterize", "Rasterize…", @@ -124,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 ), @@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) { // ---------- Reset Bounding Box ---------- /// Squares each selected object and every object inside it: the children of groups, compound paths, -/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. +/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A +/// path of a compound path selected on its own is squared alone, as the transforms move it alone. fn reset_bounding_box(s: &mut Session, _: &Value) -> Result { - let ids = selected_roots(s)?; + let ids = selected_roots_to_transform(s)?; let d = &s.doc()?.doc; let mut changed = 0; let squared: Vec<(NodeId, Node)> = ids @@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result { Ok(json!({ "changed": changed })) } +// ---------- Rotate Bounding Box ---------- + +/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle` +/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box +/// turns by what takes it there, and so do the boxes of the objects inside it (the children of +/// groups and the art of linked opacity masks), which keep their angle relative to it. +fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.rotateBoundingBox"; + // A JSON number is always finite. + let angle = f64_req(p, "angle", C)?; + let absolute = switch_or(p, "absolute", false, C)?; + // The same objects the transforms move: a path of a compound path selected on its own turns + // its own box. Layers are left out, as they have no box. + let owners = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let start = if absolute { 0.0 } else { d.bbox_angle(&owners) }; + // An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it. + let target = match vectorcraft_geom::normalize_deg(start + angle) { + a if a.abs() <= BOX_EPS_DEG => 0.0, + a => a, + }; + let mut changed = 0; + let turned: Vec<(NodeId, Node)> = owners + .iter() + .filter_map(|id| { + let n = d.node(*id)?; + let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle); + (by.abs() > BOX_EPS_DEG).then(|| { + let mut c = n.clone(); + c.turn_boxes(by); + // The selected object's box is set to the target itself, so repeated turns add no + // rounding error to it. + c.bbox_angle = target; + changed += boxes(&c); + (*id, c) + }) + }) + .collect(); + if !turned.is_empty() { + s.edit("Rotate Bounding Box", |d, _| { + for (id, n) in turned { + if let Some(slot) = d.node_mut(id) { + *slot = n; + } + } + Ok(()) + })?; + } + Ok(json!({ "angle": target, "changed": changed })) +} + +/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them. +const BOX_EPS_DEG: f64 = 1e-6; + +/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children +/// and the art of a linked opacity mask, layers left out. +fn boxes(n: &Node) -> usize { + let own = usize::from(!n.is_layer()); + let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum(); + let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art)); + own + children + mask +} + /// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in /// it stands at an angle, and the number of objects squared. The subtree takes in children and the /// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only @@ -897,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 @@ -907,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 { @@ -966,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 cb22ac160d..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,86 @@ 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(()), + } +} + +/// The error for a linked file the package would copy with an Export for Screens folder outside +/// the read roots in the native document it is or carries. +const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots"; + +/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when +/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder +/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not +/// rewritten, would name it. The error names no file or folder. +fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { + if crate::file_access::current().is_none() { + return Ok(()); + } + match carried_document(name, bytes) { + 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(()), } } @@ -363,6 +422,7 @@ impl<'a> Collector<'a> { options.profiles = saved.profiles; options.compress = compressed; options.include_linked = include_linked; + let nested = super::fileio::with_readable_settings_folder(&nested); match vectorcraft_format::save_with(&nested, &options) { Ok(rewritten) => bytes = rewritten, Err(e) => self.warn( @@ -381,6 +441,7 @@ impl<'a> Collector<'a> { } } } + check_carried_folder(&file.name, &bytes)?; let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) }; self.copies.insert(found_path.to_string(), copy.clone()); local.insert(file.path.clone(), copy); @@ -478,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 { @@ -520,23 +584,26 @@ fn prepare(s: &mut Session, p: &Value) -> Result { } let root = folder.map(|f| Path::new(f).join(&name)); let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None }; + // The package's document leaves out an Export for Screens folder outside the read roots. 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/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index aa83466693..769cb530b0 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,14 +67,14 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids` and passing over a threaded frame's first paragraph when it continues from the frame before, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches but such a continued first paragraph, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), cmd!( "text.convertListToText", "Convert to Text", - [], + ["Type"], None, "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, @@ -482,6 +482,66 @@ fn list_level_param(p: &Value, cmd: &str) -> Result> { } } +/// The number a numbered paragraph is given, from `startNumber` (a whole number from 1 to +/// [`vectorcraft_doc::text::MAX_LIST_START`]) or `restartNumbering` (true: 1): `Some(Some(n))`, +/// or `Some(None)` for `restartNumbering` false, which numbers paragraphs on from the one before. +/// None without either; giving both is an error. +fn list_start_param(p: &Value, cmd: &str) -> Result>> { + let (key, other) = ("startNumber", "restartNumbering"); + let start = p.get(key).filter(|v| !v.is_null()); + let restart = p.get(other).filter(|v| !v.is_null()); + if start.is_some() && restart.is_some() { + return Err(bad(cmd, format!("give `{key}` or `{other}`, not both"))); + } + if let Some(v) = start { + let (min, max) = (1, vectorcraft_doc::text::MAX_LIST_START); + return match v.as_f64() { + Some(x) if x.fract() == 0.0 && (f64::from(min)..=f64::from(max)).contains(&x) => Ok(Some(Some(x as u32))), + Some(x) => Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))), + None => Err(bad(cmd, format!("`{key}` must be a whole number"))), + }; + } + // `check_switches` has already refused a value that is not true or false. + Ok(restart.and_then(Value::as_bool).map(|on| on.then_some(1))) +} + +/// Take the number its list gives a paragraph away from paragraphs `paras` of `t` (indices; +/// None: every paragraph), so they count on from the paragraph before. A first paragraph that +/// continues from the frame before ([`TextObject::first_para_continues`]) keeps its number: its +/// item begins in that frame. +/// +/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues +fn clear_list_start(t: &mut vectorcraft_doc::text::TextObject, paras: Option>) { + let mut paras = paras.unwrap_or(0..t.paragraph_count()); + if paras.start == 0 && t.first_para_continues { + paras.start = 1; + } + if paras.is_empty() { + return; + } + t.edit_paras(Some(paras), |p| { + if let Some(l) = p.list.as_mut() { + l.start = None; + } + }); +} + +/// Among paragraphs `paras` of `t` (indices; None: every paragraph), the first numbered paragraph +/// that holds text and the first numbered paragraph: where a number from [`list_start_param`] can go. +/// A first paragraph that continues from the frame before ([`TextObject::first_para_continues`]) is +/// skipped: its item begins in that frame. +/// +/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues +fn list_start_candidates(t: &vectorcraft_doc::text::TextObject, paras: Option>) -> (Option, Option) { + let paras = paras.unwrap_or(0..t.paragraph_count()); + let text = t.plain_text(); + let pieces: Vec<&str> = text.split('\n').collect(); + let mut numbered = paras.filter(|&i| !(i == 0 && t.first_para_continues) && t.para_at(i).list.is_some_and(|l| l.number.is_some())).peekable(); + let first = numbered.peek().copied(); + let with_text = numbered.find(|&i| pieces.get(i).is_some_and(|s| !s.is_empty())); + (with_text, first) +} + /// Set the Warichu and Warichu Settings of `st` that are given: Warichu on or off, Lines, Line Gap /// (in the type's own units), Scale and Alignment. fn set_warichu( @@ -523,6 +583,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "koreanLineBreakAnywhere", "bunriKinshi", "kurikaeshiMojiShori", + "restartNumbering", ], C, )?; @@ -582,6 +643,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "number", "listAlign", "listLevel", + "startNumber", + "restartNumbering", "hyphenate", "wordsLongerThan", "afterFirst", @@ -762,6 +825,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { .map(|a| if a == "right" { vectorcraft_doc::text::ListAlign::Right } else { vectorcraft_doc::text::ListAlign::Left }); // …and `listLevel` the level of every list paragraph, 1 to 9. let list_level = list_level_param(p, C)?; + // …and `startNumber` or `restartNumbering` the number of the first numbered paragraph. + let list_start = list_start_param(p, C)?; let indents_given = num("leftIndent").is_some() || num("firstLineIndent").is_some(); let spacing = |k: &str| spacing_param(p, k, C); let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?); @@ -885,9 +950,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result { // A numbered list for list "number", or without `list` for a number style. let numbered = list == Some("number") || (list.is_none() && number.is_some()); // The list's other settings (the marker's alignment) stay as they were. + // A paragraph made bulleted keeps no number of its own. para.list = on.then(|| vectorcraft_doc::text::ParaList { bullet: bullet.flatten().or(had.map(|l| l.bullet)).unwrap_or_default(), number: numbered.then(|| number.flatten().or(had.and_then(|l| l.number)).unwrap_or_default()), + start: had.and_then(|l| l.start).filter(|_| numbered), ..had.unwrap_or_default() }); // A paragraph that joins a list with no left or first-line indent gets a @@ -912,6 +979,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let d = &mut doc; // The paragraph change, for the graph labels to keep. let mut para_change = None; + // Where the number `startNumber` or `restartNumbering` gives goes: the first numbered + // paragraph with text the call touches, through every target, else the first numbered one. + let (mut start_with_text, mut start_first) = (None, None); let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")); for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; @@ -1021,14 +1091,36 @@ fn set_format(s: &mut Session, p: &Value) -> Result { para.composer = v; } }; - t.edit_paras(span, |para| paras(para, &mut out_of_order)); + t.edit_paras(span.clone(), |para| paras(para, &mut out_of_order)); if let Some(name) = out_of_order { return Err(out_of_order_error(name)); } + match list_start { + Some(None) => clear_list_start(t, span), + Some(Some(_)) if start_with_text.is_none() => { + let (with_text, first) = list_start_candidates(t, span); + start_with_text = with_text.map(|i| (*id, i)); + start_first = start_first.or(first.map(|i| (*id, i))); + } + _ => {} + } super::typecmd::refresh_bounds(t); changed |= *t != before; para_change = Some(paras); } + if let Some(Some(n)) = list_start + && let Some((id, i)) = start_with_text.or(start_first) + && let Some(NodeKind::Text(t)) = d.node_mut(id).map(|node| &mut node.kind) + { + let before = t.clone(); + t.edit_paras(Some(i..i + 1), |p| { + if let Some(l) = p.list.as_mut() { + l.start = Some(n); + } + }); + super::typecmd::refresh_bounds(t); + changed |= *t != before; + } // Graph labels keep a change made to all of their text through the graph being drawn again. if range.is_none() { let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0)); diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 6ca407880c..7493f95632 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,20 +362,34 @@ 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(()), } } /// Parameters a command takes instead of one another: (command, key, other key). Giving both, /// neither null, is a parameter error ([`check_exclusive_keys`]). -const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")]; +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"), +]; /// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter /// error naming the pair. -fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> { +pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> { let given = |key: &str| params.get(key).filter(|v| !v.is_null()); for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) { if given(key).is_some() && given(other).is_some() { @@ -929,9 +1056,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/pathops.rs b/crates/engine/src/cmd/pathops.rs index 70de82fa65..cb60409f17 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Unite", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Unite) ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Minus Front", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusFront) ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Intersect", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Intersect) ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Exclude", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Exclude) ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Minus Back", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusBack) ), @@ -285,6 +285,37 @@ impl Style { } } +/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds +/// a line or another open path that encloses no area once closed, and so does not change the result's +/// shape (the result still takes its paint from the frontmost object, as without the warning). +pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first"; + +/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd +/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed +/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it. +fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool { + path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| { + // A point or a straight two-anchor line needs no area measurement. + if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) { + return true; + } + let mut closed = sp.clone(); + closed.closed = true; + // 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)) && po::area(&PathData::single(closed), rule) <= 0.0 + }) +} + +/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it. +fn closed_area(path: &PathData, rule: FillRule) -> f64 { + let mut closed = path.clone(); + for sp in &mut closed.subpaths { + sp.closed = true; + } + po::area(&closed, rule) +} + /// All subpaths of a path or compound path node, in document coordinates, with its fill rule. pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> { match &n.kind { @@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result { let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop); let label = pf_label(op); let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?; - let ids = s.edit(label, |d, sel| { + let (ids, no_area) = s.edit(label, |d, sel| { // Build the stack (back → front); names are separate from paint/style identity. + let mut no_area = false; let mut styles: Vec, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, + Pausable { f: crate::interp::PausableFn, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, @@ -213,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), @@ -311,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/host.rs b/crates/js/src/host.rs index fb980843e8..4c18d0f76f 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -447,7 +447,12 @@ impl Interp { Ok(units) => self.prepare_source(units.len().saturating_sub(floor)), Err(_) => Ok(()), }; - rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval))) + rest.map(|()| { + units.and_then(|units| { + self.observe_code(&units); + self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval) + }) + }) }); let code = code.and_then(|c| c); self.source_tag = tag; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 700efddfb2..21cd2c0bc5 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -673,6 +673,24 @@ fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unkn assert_eq!(r.error_source(), 0, "a syntax error is in the script"); } +#[test] +fn the_code_observer_sees_every_source_evaluated_at_run_time() { + let mut r = realm(10_000_000); + let seen = Rc::new(RefCell::new(Vec::::new())); + let s = seen.clone(); + r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units))); + let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap(); + assert_eq!(out, JsValue::Number(49.0)); + let want = ["1 + 1", "2", "(function anonymous(a\n) {\nreturn a\n})", "40 + 2"]; + assert_eq!(*seen.borrow(), want, "the script's own text is not observed"); + seen.borrow_mut().clear(); + r.run("eval(7); Function.prototype.toString.call(f)").unwrap(); + assert!(seen.borrow().is_empty(), "eval of a value that is not a string compiles nothing"); +} + #[test] fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { let mut r = realm(10_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 7e21bf9fdf..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 { @@ -162,6 +185,34 @@ pub(crate) struct Frame { /// Where the exception being thrown was raised: the code and the instruction. type ThrowSite = (Rc, usize); +/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. +pub(crate) type CodeObserver = Rc; + +/// A built-in function that may wait for the host ([`crate::heap::Func::Pausable`]): it is given +/// `this` and the arguments, and gives the host call it makes. +pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; + +/// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the +/// answer, and gives the result of its call. +pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; + +/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to +/// `resume` with `keep`, at once when the host answers at once. When the host waits +/// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on +/// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +pub(crate) struct Pause { + pub(crate) host: Value, + pub(crate) args: Vec, + pub(crate) keep: Vec, + pub(crate) resume: ResumeFn, +} + +/// A [`Pause`] whose host call waits for its answer. +pub(crate) struct Resumption { + resume: ResumeFn, + keep: Vec, +} + pub(crate) struct Interp { pub(crate) heap: Heap, pub(crate) stack: Vec, @@ -222,6 +273,9 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before + /// the next instruction runs. + pub(crate) resuming: Option, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -230,6 +284,9 @@ pub(crate) struct Interp { pub(crate) source_tag: u32, /// The sources [`crate::HostItem::Evaluator`] functions have given in this realm. pub(crate) evaluated: u32, + /// Called with the source text given to `eval`, `Function` and evaluator functions, before it + /// is compiled ([`crate::Realm::observe_code`]). + pub(crate) code_observer: Option, /// The tag of the source the last run's error was raised in. pub(crate) error_tag: u32, /// Where `$.line` and `$.stack` find the file and line of a compiled line. @@ -470,10 +527,12 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, evaluated: 0, + code_observer: None, error_tag: crate::realm::UNKNOWN_SOURCE, locator: None, thrown_mark: None, @@ -502,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 { @@ -679,6 +757,7 @@ impl Interp { let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); + roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -743,6 +822,14 @@ impl Interp { fn step(&mut self) -> JsResult> { self.tick()?; + // A built-in that waited for the host takes the answer on top of the stack before the + // instruction after its call runs; what it throws is thrown at that call. + if let Some(r) = self.resuming.take() { + let answer = self.pop()?; + let v = self.resume(r, answer)?; + self.push(v)?; + return Ok(None); + } let frame = self.frame_mut()?; let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") }; frame.pc += 1; @@ -774,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(); } @@ -2162,6 +2249,16 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } + Func::Pausable { f: native, .. } => { + let mark = self.temp_roots.len(); + self.temp_roots.push(this.clone()); + self.temp_roots.extend(args.iter().cloned()); + let held = self.held_bytes; + let r = native(self, this, &args).and_then(|p| self.ask(p)); + self.held_bytes = held; + self.temp_roots.truncate(mark); + return Ok(Prepared::Done(r?)); + } Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. @@ -2387,6 +2484,41 @@ impl Interp { Ok(a) } + /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host + /// function is called as the script's own code calls it, so it may wait; then the resume + /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands + /// in for that answer is the call's result for now. + fn ask(&mut self, p: Pause) -> JsResult { + let Pause { host, args, keep, resume } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + self.resume(r, answer) + } + + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let mark = self.temp_roots.len(); + self.temp_roots.push(answer.clone()); + self.temp_roots.extend(r.keep.iter().cloned()); + let v = (r.resume)(self, &r.keep, answer); + self.temp_roots.truncate(mark); + v + } + /// Calls `f` from Rust and returns its result, running the loop again for a function written /// in JavaScript. pub(crate) fn call(&mut self, f: &Value, this: &Value, args: &[Value]) -> JsResult { @@ -2435,6 +2567,13 @@ impl Interp { crate::to_utf16(text, &self.remaining_source_options()).map_err(CompileError::Syntax) } + /// Gives `units`, source a script evaluates at run time, to the realm's code observer. + pub(crate) fn observe_code(&self, units: &[u16]) { + if let Some(f) = &self.code_observer { + f(units); + } + } + /// Parses and compiles source for eval code or a script, counting it against the source /// limit. pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result, CompileError> { @@ -2473,6 +2612,7 @@ impl Interp { self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?; self.prepare_source(s.len())?; let units = self.flat_reserved(s)?; + self.observe_code(&units); let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; 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 4146ae891b..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); @@ -251,6 +255,7 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -268,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 }), } } @@ -286,20 +291,24 @@ impl Realm { interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.resuming = None; interp.passing = Value::Undefined; match result { 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 }), } } @@ -321,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); @@ -375,12 +390,20 @@ impl Realm { } /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next - /// [`Realm::advance`] goes on from there. A result past the heap limit ends the run with that + /// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the + /// call, the built-in takes `d` first and gives its own result, and what it throws is thrown + /// at its call. A result past the heap limit ends the run with that /// limit, and with no call waiting this gives an internal error. 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. @@ -468,10 +491,12 @@ impl Realm { /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, - /// `encode`, `decode`, `encodingAvailable`, `current` and `locations`, with the values `system` - /// and `lineFeed` and the messages `text.notOpen`, `text.noWrites`, `text.noPicker` and - /// `text.badMode`. Each object keeps its path, its `error` text, its open file's id, its - /// encoding and its line feed in properties that are not enumerable. + /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `pick` (the file + /// dialogs, where a run may wait), `encode`, `decode`, `encodingAvailable`, `current` and + /// `locations`, with the values `system` and `lineFeed` and the messages `text.notOpen`, + /// `text.badMode`, `text.noAlias` and `text.noHidden`. Each object keeps its path, its `error` + /// text, its open file's id, its encoding and its line feed in properties that are not + /// enumerable. pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { match crate::file_classes::install(&mut self.interp, items) { Ok(()) => Ok(()), @@ -543,6 +568,14 @@ impl Realm { self.interp.date_host.offset = std::rc::Rc::new(offset); } + /// Calls `observe` with the text of each source the realm's scripts evaluate at run time, before + /// it is compiled: a string given to `eval` (direct or indirect), the parameters and body + /// `Function` joins, and a source an evaluator host function + /// ([`crate::HostItem::Evaluator`]) gives. Replaces an earlier observer. + pub fn observe_code(&mut self, observe: impl Fn(&[u16]) + 'static) { + self.interp.code_observer = Some(std::rc::Rc::new(observe)); + } + /// Collects garbage now and returns the heap's estimated size in bytes afterwards. pub fn collect_garbage(&mut self) -> usize { self.interp.collect_garbage(); diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 8bd8afc2e5..db6c51d47d 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -45,10 +45,15 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ "{folder?, zip?, artboards? | range? | fullDocument? | assets?, includeBleed?, includeArtboardFill?, subfolders?, preset?, formats?, settings?, prefix?} = document.exportForScreens (no folder → the files, or one zip, as dataBase64)", ), ("tool.select", "Select Tool", "{tool} e.g. selection, directSelection, pen, rectangle, ellipse, polygon, star, lineSegment"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool) → {tool}", + ), ( "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", ), ]; @@ -165,6 +170,7 @@ impl Headless { "file.export" => self.export(params), "file.exportForScreens" => self.session.execute("document.exportForScreens", params).map_err(|e| e.to_string()), "tool.select" => self.select_tool(params), + "tool.selectLastSelection" => self.select_last_selection_tool(), "tool.setOption" => self.session.set_tool_option_cmd(params), _ => self.session.execute(id, params).map_err(|e| e.to_string()), } @@ -208,6 +214,15 @@ impl Headless { Ok(json!({"tool": self.session.tool_id()})) } + /// `tool.selectLastSelection`: the selection tool chosen last, kept when it is already active. + fn select_last_selection_tool(&mut self) -> Result { + let id = self.session.last_selection_tool(); + if self.session.tool_id() != id { + self.session.select_tool(id, self.view).map_err(|e| e.to_string())?; + } + Ok(json!({"tool": self.session.tool_id()})) + } + fn apply_ui_requests(&mut self, reqs: Vec, out: &mut Vec) -> Result<(), String> { for r in reqs { match r { @@ -215,6 +230,7 @@ impl Headless { self.session.select_tool(&t, self.view).map_err(|e| e.to_string())?; } UiRequest::Dialog(k, p) => out.push(json!({"dialog": k, "params": p})), + UiRequest::Panel(panel) => out.push(json!({"panel": panel})), UiRequest::Status(msg) => out.push(json!({"status": msg})), // The place cursor's file, placed at once. UiRequest::Place(p) => { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index a6d1fe6c5d..870f4a23a3 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -17,10 +17,12 @@ mod limits; mod links; mod liquify; mod livepaint; +mod move_offsets; mod pen; mod persp; mod place; mod protocol; +mod shapewidgets; mod svg; fn server() -> Server { @@ -321,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() { @@ -1634,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(); @@ -1893,6 +1983,30 @@ fn e_during_a_marquee_gesture_selects_only_the_objects_inside() { assert_eq!(serde_json::from_str::(&text_of(&r)).unwrap()["handledBy"], "tool.select", "{r}"); } +/// `run_command tool.selectLastSelection` headless: the Selection tool before any selection tool +/// is chosen, then the selection tool chosen last; Magic Wand doesn't count. `list_commands` +/// lists it as a command the headless backend runs. +#[test] +fn select_last_selection_tool_runs_headless() { + let mut s = server(); + let mut id = 0; + let mut run = |s: &mut Server, command: &str, params: Value| { + id += 1; + let r = call(s, id, "run_command", json!({"command": command, "params": params})); + assert_eq!(r["isError"], false, "{command}: {r}"); + serde_json::from_str::(&text_of(&r)).unwrap() + }; + run(&mut s, "tool.select", json!({"tool": "pen"})); + assert_eq!(run(&mut s, "tool.selectLastSelection", json!({})), json!({"tool": "selection"})); + run(&mut s, "tool.select", json!({"tool": "groupSelection"})); + run(&mut s, "tool.select", json!({"tool": "magicWand"})); + assert_eq!(run(&mut s, "tool.selectLastSelection", json!({})), json!({"tool": "groupSelection"})); + let r = call(&mut s, 99, "list_commands", json!({"filter": "selectLastSelection"})); + let v: Value = serde_json::from_str(&text_of(&r)).unwrap(); + let listed = v["commands"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned().unwrap_or_default(); + assert_eq!((listed["host"].clone(), listed["label"].clone()), (json!(true), json!("Select Last Selection Tool")), "{v}"); +} + /// `press_key {key: "c"}` and `{key: "f"}` while an arc is being dragged go to the Arc tool, and /// the release draws one arc. With nothing dragged, C is a shortcut again. #[test] @@ -2185,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 new file mode 100644 index 0000000000..bce666d484 --- /dev/null +++ b/crates/mcp/src/tests/shapewidgets.rs @@ -0,0 +1,102 @@ +//! 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; + +use crate::{Backend, Headless, call_tool}; + +fn ok(h: &mut Headless, name: &str, args: Value) -> Value { + let r = call_tool(h, name, &args); + assert!(!r.is_error, "{name} {args}: {r:?}"); + serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap_or(Value::Null) +} + +#[test] +fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + ok(&mut h, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 100})); + let st = h.session.doc().unwrap(); + let w = CornerWidgets::showing(&st.doc, &st.selection, h.view.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let steps = st.history.undo.len(); + let dbl = ok(&mut h, "pointer_gesture", json!({"tool": "rectangle", "events": [{"kind": "doubleclick", "x": at.x, "y": at.y}]})); + assert_eq!(dbl["requests"], json!([{"panel": "transform"}]), "{dbl}"); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps, "no undo step"); + // Off the widgets, the double-click asks for nothing. + 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..fcbc9cf708 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}) } @@ -214,6 +219,7 @@ pub fn tool_definitions() -> Vec { "tiltX": num("Pen tilt in degrees −90..90, positive leaning right (document axes); with tiltY, the tilt the Paintbrush records for Tilt and Bearing brushes. One without the other is 0"), "tiltY": num("Pen tilt in degrees −90..90, positive leaning down the page"), "rotation": num("Pen barrel rotation in degrees clockwise: the rotation the Paintbrush records for Rotation brushes"), + "wheel": num("Airbrush pen finger wheel 0..1 (clamped): the wheel the Paintbrush records for Stylus Wheel brushes"), "holdMs": num("Milliseconds the pointer then holds still, button down (0..60000): Twirl, Pucker and Bloat keep applying"), }), &["kind", "x", "y"]), }, @@ -466,20 +472,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 b6da21331e..8e1da7dcf2 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?}"), ( @@ -233,7 +255,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), - ("type.hiddenCharacters", "Show Hidden Characters", "Cmd+Alt+I", "{} toggle markers for spaces, paragraph ends and story ends"), + ( + "type.hiddenCharacters", + "Show Hidden Characters", + "Cmd+Alt+I", + "{} toggle markers for spaces, tabs, nonbreaking and fixed-width spaces, discretionary hyphens, forced line breaks, paragraph ends and story ends", + ), ("type.alignLeft", "Align left", "Cmd+Shift+L", "{} align the selected type's paragraphs (or those the Type tool's selection touches) left"), ( "type.alignCenter", @@ -260,7 +287,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.bulletsAndNumbering", "Bullets and Numbering…", "", - "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", + "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt), startAt (bool: the Numbers tab's Start at box, on when the paragraphs have the same number of their own, blank when those differ; on sends startNumber, off sends restartNumbering false), startNumber (1..999999999: its number, 1 until one is typed)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", ), ( "type.convertListToText", @@ -358,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", @@ -376,6 +421,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+Alt+Shift+F", "{} show the Character panel if it is hidden and open its font family menu, whose search field takes the keyboard focus: type to search, Enter applies the highlighted font → {field: \"fontName\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", ), + ( + "type.highlightFontSize", + "Highlight Font Size", + "", + "{} (Type › Size › Other…) show the Character panel if it is hidden and give its Font Size field the keyboard focus with its value selected (blank where the selected sizes differ): type a size and press Enter → {field: \"fontSize\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), ( "type.highlightKerning", "Highlight Kerning", @@ -394,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", @@ -506,7 +569,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolsBesideCanvas", "Keep Tools Beside the Canvas", "", - "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", + "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Dropping a floating Tools panel on the canvas's left edge, right of panels docked on the left, turns it on, and on the window's left edge turns it off; with no panels docked on the left, or in the column both edges share beside panels collapsed to icons, a drop leaves it as it is. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", ), ( "window.floatTools", @@ -666,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", @@ -792,7 +855,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", @@ -825,11 +888,17 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ("tool.select", "Select Tool", "", "{tool: id} (see tools) → {tool}; a tool that cannot be chosen returns the error"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "Cmd+~", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows", + ), ( "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", @@ -843,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…", @@ -872,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…", @@ -925,7 +1018,13 @@ 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", + "Options of Selected Object…", + "", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", @@ -973,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", @@ -1097,7 +1196,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.navigatorPanelOptions", "Panel Options…", "", - "{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)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, 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", + "{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", @@ -1147,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", @@ -1264,7 +1375,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.expandDialog", "Expand…", "", - "{} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255)): OK runs object.expand with them as one undo step; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", + "{immediate?: bool (false)} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255), or the choices OK last expanded with since the app started): OK runs object.expand with them as one undo step and keeps them until the app quits; immediate: true (the menu item chosen with Alt/Option) runs object.expand at once with those choices (the defaults before any OK), and opens the dialog instead when none of them has something to expand in the selection; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", ), ( "attributes.openUrl", @@ -1380,6 +1491,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent", ), + ( + "ui.colorWheel", + "Color Wheel Options", + "", + "{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", "Save PDF Dialog", @@ -1455,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", @@ -1635,6 +1764,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", ), + ( + "ui.actionSet.replace", + "Replace Actions…", + "", + "{path? | data?: the file's text} read an action set file at path, else a picked one, as ui.actionSet.load reads it (.vcactions and .aia, with the same limits, errors and reports of left-out steps and unknown commands), and replace every set in the Actions panel, the built-in Default Actions set included, with the file's set, which keeps its name. The set becomes current and 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; when the panel already holds only a set that saves alike, in that state, nothing changes, the set keeps its ids and changed is false. Omitted params count as {}. Params of another type, another key, a path or data that is not a string, a file that can't be read or is refused, a canceled pick, or a replace 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 Replace Actions… (disabled where there is no open dialog, the web, and while an action records or plays) → {changed, set: 0, name, actions: n, unknownCommands?, unknownCount?, skipped?, leftOut?}", + ), ( "ui.actionSet.delete", "Delete Action Sets", @@ -1653,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", @@ -1664,7 +1805,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.epsOptionsDialog", "EPS Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + ), + ( + "ui.hpglOptionsDialog", + "HP-GL Options Dialog", + "", + "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too", ), ( "file.saveForWeb", 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/changed.rs b/crates/render/src/changed.rs index 1c15247034..cea07dab35 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -360,8 +360,8 @@ fn same_but_anchors(a: &Node, b: &Node) -> bool { } /// Does `n` paint each pixel from the segments near it alone: no effects, every visible fill and -/// stroke a solid color, and no stroke with dashes, a width profile, pressure, tilt, bearing or -/// rotation, arrowheads, a brush or effects? +/// stroke a solid color, and no stroke with dashes, a width profile, pressure, tilt, bearing, +/// rotation or wheel, arrowheads, a brush or effects? fn local_paint(n: &Node) -> bool { use vectorcraft_doc::AppearanceItem; let solid = |p: &vectorcraft_color::Paint| matches!(p, vectorcraft_color::Paint::Solid { .. } | vectorcraft_color::Paint::None); @@ -379,6 +379,7 @@ fn local_paint(n: &Node) -> bool { && s.tilt.is_none() && s.bearing.is_none() && s.rotation.is_none() + && s.wheel.is_none() && s.start_arrow.is_none() && s.end_arrow.is_none() && s.brush.is_none() 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.rs b/crates/svg/src/export.rs index ded9a037fe..84b2efa32b 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -78,6 +78,18 @@ fn update_editing_hash(svg: &mut String) { } } +/// Format physical dimensions (inches, mm, cm) with enough precision and significant digits +/// that small nonzero sizes do not round to zero or distort relative aspect ratio. +fn physical_num(v: f64) -> String { + if !v.is_finite() || v <= 0.0 { + return "0".into(); + } + let leading_zeros = (-v.log10().floor() as i32).max(0); + let decimals = (leading_zeros + 3).clamp(3, 14) as u8; + let s = fmt_num(v, decimals); + if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s } +} + /// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated /// ids starting with `id_prefix`. fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: &str) -> Output { @@ -183,10 +195,17 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("version", "1.2").attr("baseProfile", "tiny"); } if !opts.responsive { - // Unitless width/height stay in this one branch so #7105 (physical unit suffixes) can rebase here. - root = root.attr("width", &ww).attr("height", &hh); + if let Some(suffix) = doc.units.svg_suffix() { + let w_val = physical_num(doc.units.from_pt(rect.width())); + let h_val = physical_num(doc.units.from_pt(rect.height())); + root = root.attr("width", format_args!("{w_val}{suffix}")).attr("height", format_args!("{h_val}{suffix}")); + } else { + root = root.attr("width", &ww).attr("height", &hh); + } } - root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open(); + let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() }; + let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() }; + root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open(); let mut out = svg.as_str().to_string(); out.push_str(nl); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); diff --git a/crates/svg/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/svg/tests/it/import_units.rs b/crates/svg/tests/it/import_units.rs index 1ce01c7f07..0140741aeb 100644 --- a/crates/svg/tests/it/import_units.rs +++ b/crates/svg/tests/it/import_units.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Document, Node, NodeKind, Unit}; use vectorcraft_geom::Rect; -use vectorcraft_svg::import; +use vectorcraft_svg::{ExportOptions, export, import}; fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); @@ -130,3 +130,65 @@ fn absolute_lengths_in_a_pixel_document_keep_their_size() { assert!(close_rect(n.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 72.0, 720.0 / 25.4)), "{:?}", n.geometric_bounds()); assert!(close(n.appearance.stroke_width(), 2.0)); } + +#[test] +fn export_physical_units_writes_unit_suffixes() { + // Millimeters (#864 / G11: avoid 75% scale in external tools like LightBurn, LaserGRBL, Inkscape) + let mut d = Document::new(50.0 * 72.0 / 25.4, 30.0 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"50mm\" height=\"30mm\""), "{s}"); + assert!(s.contains("viewBox=\"0 0 141.732 85.039\""), "{s}"); + + // Inches + let mut d = Document::new(8.5 * 72.0, 11.0 * 72.0); + d.units = Unit::Inches; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"8.5in\" height=\"11in\""), "{s}"); + assert!(s.contains("viewBox=\"0 0 612 792\""), "{s}"); + + // Centimeters + let mut d = Document::new(5.0 * 72.0 / 2.54, 3.0 * 72.0 / 2.54); + d.units = Unit::Centimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"5cm\" height=\"3cm\""), "{s}"); + + // Picas + let mut d = Document::new(10.0 * 12.0, 20.0 * 12.0); + d.units = Unit::Picas; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"10pc\" height=\"20pc\""), "{s}"); + + // Points and pixels remain unitless + let mut d = Document::new(100.0, 200.0); + d.units = Unit::Points; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"100\" height=\"200\""), "{s}"); + + d.units = Unit::Pixels; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"100\" height=\"200\""), "{s}"); + + // Responsive export omits width and height even with physical units + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions { responsive: true, ..Default::default() }); + assert!(!s.contains("width="), "{s}"); + assert!(!s.contains("height="), "{s}"); + + // Non-zero small dimensions do not round to zero + let mut d = Document::new(0.001 * 72.0 / 25.4, 0.002 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(s.contains("width=\"0.001mm\" height=\"0.002mm\""), "{s}"); + + // Extreme small dimension below 8 decimal places preserves non-zero width and viewBox + let mut d = Document::new(1e-9 * 72.0 / 25.4, 1e-9 * 72.0 / 25.4); + d.units = Unit::Millimeters; + let s = export(&d, &ExportOptions::default()); + assert!(!s.contains("width=\"0mm\""), "{s}"); + assert!(!s.contains("viewBox=\"0 0 0 0\""), "{s}"); + + // Re-importing preserved physical units + let back = import(&s).unwrap(); + assert_eq!(back.units, Unit::Millimeters); +} 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 ef62fa2bcc..874813e9b1 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -47,6 +47,7 @@ impl Metrics { FirstBaseline::CapHeight => self.cap, FirstBaseline::XHeight => self.xh, FirstBaseline::Leading => self.lead, + FirstBaseline::EmBoxHeight => self.top, FirstBaseline::Fixed => 0.0, }; v.max(min) @@ -457,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/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 80bd7c783a..1980af6213 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1360,6 +1360,40 @@ fn inset_and_first_baseline_options() { assert!(cap.lines[0].baseline < base.lines[0].baseline && cap.lines[0].baseline > 5.0); } +/// First Baseline Em Box Height: the top of the first line's ideographic em box (the one leading +/// measured from em box top to top uses) touches the top of the type area inside the inset. On a +/// line of several sizes the largest em box decides, and a Min further down sets the baseline. +#[test] +fn em_box_height_puts_the_first_lines_em_box_top_at_the_type_area_top() { + let frame = Rect::new(0.0, 0.0, 300.0, 300.0); + let em_box = |t: &TextObject, inset: f64, min: f64| { + let opts = LayoutOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: min, inset, ..Default::default() }; + layout_with(db(), t, &opts).lines[0].baseline + }; + // The em box top the EmBoxTop leading model sets a frame's first line at. + let em_top = |t: &TextObject| { + let mut t = t.clone(); + t.para.leading_model = vectorcraft_doc::LeadingModel::EmBoxTop; + layout(db(), &t).lines[0].baseline + }; + let t = area(COPY, style(12.0), frame, Justify::Left); + let top = em_top(&t); + assert!(top > 5.0 && top < 12.0, "{top}"); + let ascent = layout(db(), &t).lines[0].baseline; + assert!((top - ascent).abs() > 0.1, "not the ascent: {top} {ascent}"); + assert!((em_box(&t, 0.0, 0.0) - top).abs() < 1e-9); + assert!((em_box(&t, 10.0, 0.0) - (10.0 + top)).abs() < 1e-9, "measured from the inset"); + // A Min nearer the top than the em box changes nothing; one further down is the baseline. + assert!((em_box(&t, 10.0, top / 2.0) - (10.0 + top)).abs() < 1e-9); + assert!((em_box(&t, 10.0, 30.0) - 40.0).abs() < 1e-9); + // 10 pt and 20 pt on the first line: the 20 pt em box top is at the top. + let mut mixed = area("small Large", style(10.0), frame, Justify::Left); + mixed.runs = vec![run("small ", 10.0), run("Large", 20.0)]; + let large = area("Large", style(20.0), frame, Justify::Left); + assert!((em_box(&mixed, 0.0, 0.0) - em_box(&large, 0.0, 0.0)).abs() < 1e-9); + assert!((em_box(&large, 0.0, 0.0) - 2.0 * top * 10.0 / 12.0).abs() < 1e-6); +} + /// `LineInfo::first_baseline`: each line that starts a column has its baseline that far below the /// column's top inside the inset, for every first baseline option, with and without a minimum and /// an inset, in both leading models, and for lines of several sizes (each line in one size). @@ -1374,8 +1408,14 @@ fn lines_starting_a_column_sit_at_their_first_baseline() { let text: String = runs.iter().map(|r| r.text.as_str()).collect(); let mut other_sizes = 0; for model in [vectorcraft_doc::LeadingModel::RomanBaseline, vectorcraft_doc::LeadingModel::EmBoxTop] { - for first_baseline in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::Fixed] - { + for first_baseline in [ + FirstBaseline::Ascent, + FirstBaseline::CapHeight, + FirstBaseline::XHeight, + FirstBaseline::Leading, + FirstBaseline::EmBoxHeight, + FirstBaseline::Fixed, + ] { for (first_baseline_min, inset) in [(0.0, 0.0), (18.0, 6.0)] { for height in [100.0, 120.0, 140.0] { let mut t = area(&text, style(12.0), Rect::new(0.0, 0.0, 420.0, height), Justify::Left); diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index dd12804e91..40c8076b2d 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -142,6 +142,32 @@ fn fit_first_line_widens_a_vertical_frame_from_its_right_edge() { assert_eq!(layout(FontDb::global(), &t).lines.len(), 1); } +/// First Baseline Em Box Height in vertical area type: the first column's em box edge touches the +/// frame's right edge inside the inset, as far in as leading measured from em box top to top sets +/// it. +#[test] +fn em_box_height_sets_a_vertical_frames_first_column_at_its_em_box() { + use vectorcraft_doc::{FirstBaseline, LeadingModel}; + let first = |fb: FirstBaseline, model: LeadingModel| { + let mut t = vertical("§§"); + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 100.0, 105.0).to_path(0.1)) }; + t.area.first_baseline = fb; + t.area.inset = 5.0; + t.para.leading_model = model; + let l = layout(FontDb::global(), &t); + (l.lines[0].baseline, l.lines[0].first_baseline) + }; + let (baseline, distance) = first(FirstBaseline::EmBoxHeight, LeadingModel::RomanBaseline); + let (em_top, _) = first(FirstBaseline::Ascent, LeadingModel::EmBoxTop); + let (ascent, ascent_distance) = first(FirstBaseline::Ascent, LeadingModel::RomanBaseline); + assert!((baseline - em_top).abs() < 1e-9, "{baseline} {em_top}"); + // Measured from the edge inside the inset, where a Fixed first baseline of 0 sits. + let (edge, _) = first(FirstBaseline::Fixed, LeadingModel::RomanBaseline); + assert!((baseline - distance - edge).abs() < 1e-9, "{baseline} {distance} {edge}"); + assert!((ascent - ascent_distance - edge).abs() < 1e-9, "{ascent} {ascent_distance} {edge}"); + assert!((baseline - ascent).abs() > 0.1, "not the ascent: {baseline} {ascent}"); +} + /// `baselines`: one per line that holds characters, along it for horizontal type and down the /// column's centre line for vertical type (where point type's anchor is); none on a path. #[test] diff --git a/crates/text/src/tests/warichu.rs b/crates/text/src/tests/warichu.rs index cbefb86bb5..7434e43db2 100644 --- a/crates/text/src/tests/warichu.rs +++ b/crates/text/src/tests/warichu.rs @@ -231,7 +231,7 @@ fn a_warichu_line_keeps_the_auto_leading_of_its_own_size() { #[test] fn the_first_baseline_measures_a_block_at_its_own_size() { use vectorcraft_doc::FirstBaseline; - for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading] { + for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::EmBoxHeight] { let baseline = |inside: CharStyle| { let mut t = area("", style(20.0), Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left); t.area.first_baseline = first; 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 d4427641b2..8d47e8226c 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, BevelProfile, 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_face_map, 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 6ef7267eae..5b61b32de4 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; @@ -290,11 +291,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 } } } @@ -321,21 +325,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", } } @@ -368,6 +375,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. @@ -456,6 +467,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 dbcd707672..157001f275 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -472,9 +472,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 3dc7c70b96..77ff240f75 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -211,8 +211,26 @@ pub struct ShapeBuilderTool { prepared: Option>, /// A gesture made while the map of a large selection is being built on another thread. deferred: Option, + /// The button went down with nothing selected: the release says what to select. + empty_press: bool, + /// The last gesture put one of [`SHAPE_BUILDER_STATUS`] in the status bar: the next gesture that + /// builds something clears it. + diagnosed: bool, } +/// The status a Shape Builder gesture gives when the selection holds no path or compound path. +pub const SELECT_PATHS: &str = "Shape Builder: select paths or compound paths"; + +/// The status a Shape Builder gesture that touched nothing gives when it ends over a path or +/// compound path that is not selected. +pub const SELECT_ALL_PATHS: &str = "Shape Builder: select all paths you want to merge"; + +/// The status a Shape Builder gesture that touched nothing gives anywhere else. +pub const NO_REGION: &str = "Shape Builder: no region under the pointer"; + +/// The status messages the Shape Builder tool gives. +pub const SHAPE_BUILDER_STATUS: [&str; 3] = [SELECT_PATHS, SELECT_ALL_PATHS, NO_REGION]; + /// A Shape Builder gesture made while the map of the selection was being built on another /// thread: the map key and the inputs it was made over, its pointer events, which [`Tool::poll`] /// replays once the map is there, and whether the release has come. @@ -455,6 +473,26 @@ impl ShapeBuilderTool { } } + /// Why a gesture released at `p` that touched nothing built nothing: the selection gives no path + /// or compound path ([`SELECT_PATHS`]); the pointer is over a path or compound path that a click + /// can pick and that is neither selected nor inside a selected object ([`SELECT_ALL_PATHS`]); or + /// neither ([`NO_REGION`]). + fn nothing_built(&mut self, cx: &ToolContext, p: Point) -> Action { + self.diagnosed = true; + if self.cache.get(cx, self.opts.open_filled_as_closed).shapes.is_empty() { + return Action::Status(SELECT_PATHS.into()); + } + let unselected = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| { + let chain: Vec = h.ancestry.iter().copied().chain([h.leaf]).collect(); + let path = chain + .iter() + .filter_map(|id| cx.doc.node(*id)) + .any(|n| matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })); + path && !chain.iter().any(|id| cx.selection.contains(*id)) + }); + Action::Status(if unselected { SELECT_ALL_PATHS } else { NO_REGION }.into()) + } + /// The cursor swatch preview: the swatch before the current fill, the current fill (ringed) /// and the swatch after it, side by side above the pointer. fn swatch_chips(&self, cx: &ToolContext) -> Vec { @@ -479,7 +517,9 @@ impl Tool for ShapeBuilderTool { vec![] } PointerKind::Down => { - // While a merge is being computed, a press starts no gesture. + // While a merge is being computed, a press starts no gesture. With nothing + // selected, the release says what to select. + self.empty_press = cx.selection.is_empty() && !self.editing(); if cx.selection.is_empty() || self.editing() { return vec![]; } @@ -564,7 +604,7 @@ impl Tool for ShapeBuilderTool { let press = points.first().copied().filter(|s| marquee.is_none() && !self.far && s.distance(p) <= cx.tol(CLICK_TOL_PX)); let split = press.filter(|q| self.stroke_at(cx, *q, erase).is_some()); if std::mem::take(&mut self.touched).is_empty() && split.is_none() { - return vec![]; + return vec![self.nothing_built(cx, p)]; } self.stroke = None; let roots = sorted_roots(cx.doc, &cx.selection.objects); @@ -590,11 +630,17 @@ impl Tool for ShapeBuilderTool { if self.opts.swatches { params["pickColorFrom"] = json!("swatches"); } + // The gesture builds something: the reason the last one built nothing goes. + let mut acts: Vec = std::mem::take(&mut self.diagnosed).then(|| Action::Status(String::new())).into_iter().collect(); // A large selection's merge is computed on another thread; `poll` applies it. - if self.start_merge(cx, ¶ms) { - return vec![]; + if !self.start_merge(cx, ¶ms) { + acts.push(Action::Exec("shapeBuilder.merge".into(), params)); } - vec![Action::Exec("shapeBuilder.merge".into(), params)] + acts + } + PointerKind::Up if std::mem::take(&mut self.empty_press) => { + self.diagnosed = true; + vec![Action::Status(SELECT_PATHS.into())] } _ => vec![], } @@ -693,6 +739,7 @@ impl Tool for ShapeBuilderTool { /// Choosing another tool or another document applies the merge being computed first. fn deactivate(&mut self, cx: &ToolContext) -> Vec { + self.empty_press = false; self.finish_edit(cx) } @@ -735,9 +782,11 @@ impl Tool for ShapeBuilderTool { /// With Pick Color From Color Swatches, the Left and Right arrow keys pick the color swatch /// before or after the current fill. Escape during a drag cancels it: the release after it - /// merges and deletes nothing. + /// merges and deletes nothing, and Escape while a press with nothing selected is held keeps its + /// release from showing a status. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) || (self.dragging && key == ToolKey::Escape) + (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) + || ((self.dragging || self.empty_press) && key == ToolKey::Escape) } /// The arrows pick swatches only without modifiers; Shift, Alt and Cmd/Ctrl arrows keep their @@ -753,6 +802,7 @@ impl Tool for ShapeBuilderTool { } if key == ToolKey::Escape { self.dragging = false; + self.empty_press = false; self.points.clear(); self.touched = Touched::default(); // A gesture recorded while the map is being built is canceled with it. @@ -808,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 78d1c0b838..dc31c1ba79 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -471,6 +471,106 @@ fn shape_builder_hover_builds_a_small_map_at_once() { assert_eq!((t.cache.builds, t.cache.background), (1, 0)); } +fn status(msg: &str) -> Vec { + vec![Action::Status(msg.into())] +} + +/// A click or drag with nothing selected shows what to select when it is released, and Escape +/// during the press keeps the release quiet. +#[test] +fn shape_builder_with_nothing_selected_says_what_to_select() { + let (d, _, _) = two_rects(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS), "a click"); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 125.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_PATHS), "a drag"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)).is_empty(), "a release without a press"); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)).is_empty(), "a canceled press"); + assert!(!t.claims_key(&cx, ToolKey::Escape)); +} + +/// With A of the overlapping squares A and B selected, a click on the part of B outside A builds +/// nothing and says to select every path to merge; a click on empty canvas says there is no +/// region; a click inside A still merges A alone and clears that status, and the click after it +/// gives the merge alone. +#[test] +fn shape_builder_names_the_unselected_path_under_a_release_that_built_nothing() { + let (d, a, _) = two_rects(); + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_ALL_PATHS)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION)); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!( + matches!(acts.as_slice(), [Action::Status(m), Action::Exec(id, v)] if m.is_empty() && id == "shapeBuilder.merge" && v["ids"] == json!([a.0])), + "{acts:?}" + ); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "shapeBuilder.merge"), "{acts:?}"); + // A locked or hidden B cannot be picked, so the release says there is no region. + for hide in [false, true] { + let (mut d, a, b) = two_rects(); + let n = d.node_mut(b).unwrap(); + if hide { + n.visible = false; + } else { + n.locked = true; + } + let mut s = Selection::default(); + s.set([a]); + let cx = crate::testutil::cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(NO_REGION), "hidden: {hide}"); + } +} + +/// A selection that holds no path or compound path says to select one. +#[test] +fn shape_builder_with_no_path_selected_says_to_select_paths() { + let (mut d, a, _) = two_rects(); + d.node_mut(a).unwrap().locked = true; + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS)); +} + +/// A gesture made while the map of a large selection is being built and released over nothing +/// gives its status once, when it is replayed. +#[test] +fn shape_builder_replayed_gesture_over_nothing_gives_its_status_once() { + let (d, s) = square_row(200); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, 15.0, 10.0)); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 450.0, 450.0)).is_empty()); + assert_eq!(t.cache.builds, 0, "the gesture did not wait for the map"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 450.0, 450.0)).is_empty(), "the gesture waits for the map"); + assert!(t.editing()); + assert_eq!(t.finish_edit(&cx), status(NO_REGION)); + assert!(t.finish_edit(&cx).is_empty() && !t.editing()); +} + #[test] fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let (d, a, b) = two_rects(); @@ -485,7 +585,7 @@ fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let Action::Exec(_, v) = &acts[0] else { panic!() }; assert_eq!(v["erase"], true); t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION), "the release edits nothing and says why"); } /// Squares A (0..100) and B (50..150 both ways), overlapping at a corner, selected. @@ -998,9 +1098,9 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, 0.5, 27.0)); let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; assert_eq!((&v["splitStroke"], &v["points"]), (&json!(true), &json!([[-1.0, 25.0]]))); - // A release farther away is a drag, which splits nothing. + // A release farther away is a drag, which splits nothing and says it touched no region. t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)), status(NO_REGION)); // So is a Straight Line drag that goes away and ends back near the press. t.set_option("selection", &json!("straightLine")); t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); @@ -1008,11 +1108,12 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, -0.5, 25.5)); assert!(!acts.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("splitStroke").is_some())), "{acts:?}"); t.set_option("selection", &json!("freeform")); - // A drag merges as before and sends no switch. + // A drag merges as before and sends no switch; it clears the status the drag before it gave. t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0)); t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 75.0)); let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 75.0)); - let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + let [Action::Status(m), Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(m.is_empty(), "{m}"); assert!(v.get("splitStroke").is_none(), "{v}"); } @@ -1032,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 529aa80d18..cd6cbf627a 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.rs b/crates/tools/src/draw2.rs index 9401dcd4c2..2b1ed3fd80 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -102,17 +102,18 @@ pub(crate) fn pen_bearing(q: PenPose) -> Option { (from_upright >= 1.0).then(|| (-y).atan2(x).to_degrees()) } -/// The 0..1 that each of the Eraser's variation modes Pressure, Tilt, Bearing and Rotation reads -/// from a pen at `pressure` (0..1) held as `pose`, leaning toward `bearing` (degrees, from -/// [`pen_bearing`]): 0 gives the value less its variation and 1 the value plus it, as -/// `path.eraseRegion` reads a stroke's points. Tilt reads 1 upright and 0 lying flat; Bearing and -/// Rotation read ½ plus the angle over 360°, the rotation turned counter-clockwise. What the pen -/// does not give reads ½, the value itself. -pub(crate) fn pen_controls(pressure: f64, pose: Option, bearing: Option) -> [f64; 4] { +/// The 0..1 that each of the Eraser's variation modes Pressure, Tilt, Bearing, Rotation and Stylus +/// Wheel reads, in that order, from a pen at `pressure` (0..1) held as `pose`, leaning toward +/// `bearing` (degrees, from [`pen_bearing`]): 0 gives the value less its variation and 1 the value +/// plus it, as `path.eraseRegion` reads a stroke's points. Tilt reads 1 upright and 0 lying flat; +/// Bearing and Rotation read ½ plus the angle over 360°, the rotation turned counter-clockwise; +/// Stylus Wheel reads the pen's wheel (0..1). What the pen does not give reads ½, the value itself. +pub(crate) fn pen_controls(pressure: f64, pose: Option, bearing: Option) -> [f64; 5] { let tilt = pose.and_then(|q| q.tilt).map_or(0.5, |t| 1.0 - pen_lean(t).1 / 90.0); let rotation = pose.and_then(|q| q.rotation).map_or(0.5, |r| 0.5 + vectorcraft_geom::normalize_deg(-f64::from(r)) / 360.0); let bearing = bearing.map_or(0.5, |b| 0.5 + b / 360.0); - [pressure, tilt, bearing, rotation].map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 }) + let wheel = pose.and_then(|q| q.wheel).map_or(0.5, f64::from); + [pressure, tilt, bearing, rotation, wheel].map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 }) } /// Create a drawing tool by id (None = not one of ours). diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 58664704ad..1fe1fd72f3 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -4,13 +4,15 @@ //! 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 //! the anchor, handles and all, as while drawing with the Pen. Blend spine points and handles //! follow the same conversions (#2544). -//! Scissors: click a path to split it there (Alt = add, as the Add Anchor Point tool does). +//! Scissors: hover and click snap as the Pen does; click a path to split it there (Alt = add, +//! as the Add Anchor Point tool does). use serde_json::json; use vectorcraft_doc::NodeId; @@ -18,8 +20,8 @@ use vectorcraft_geom::Point; use super::{hit_anchor, hit_segment, insert_anchor, remove_anchor}; use crate::direct::hit_handle; -use crate::guides::HandleSnap; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use crate::guides::{DrawSnap, HandleSnap}; +use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; use vectorcraft_geom::constrain_angle_from; #[derive(Clone, Copy, Debug)] @@ -93,16 +95,32 @@ enum SpaceResume { SpineHandle { id: NodeId, ai: usize, out: bool }, } +/// The cursor reuses the last hover's point, with DrawSnap checking its target inputs. The +/// Scissors-only inputs also bind the resolved point to the current cut eligibility. +struct ScissorsHover { + raw: Point, + snapped: Point, + zoom: f64, + isolation: Option, + selection_tolerance: f64, +} + pub struct AnchorTool { id: &'static str, state: State, /// Smart guides of the handle being dragged, and what it snaps to. guides: Vec, snap: HandleSnap, + /// Scissors uses the drawing tools' targets; Anchor Point keeps its own handle snap above. + scissors_snap: DrawSnap, + scissors_hover: Option, /// Move offset while Shift-dragging an anchor or spine point (pointer, delta). 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 +131,98 @@ 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(), + scissors_snap: DrawSnap::default(), + scissors_hover: None, + measure: None, + space_resume: None, + lent: false, + } + } + + fn clear_scissors_snap(&mut self) { + self.scissors_snap.clear(); + self.scissors_hover = None; + } + + fn current_scissors_hover(&self, cx: &ToolContext) -> Option<&ScissorsHover> { + self.scissors_hover.as_ref().filter(|h| { + h.zoom == cx.zoom + && h.isolation == cx.isolation + && h.selection_tolerance == cx.selection_tolerance + && self.scissors_snap.is_current(cx, &[]) + }) + } + + /// Keep a shared art snap unless it prevents a cut the raw pointer could make. Outside art + /// still supplies alignment and intersection guides; pixel and grid snapping keep precedence. + fn resolve_scissors_snap(&mut self, cx: &ToolContext, raw: Point, snapped: Point) -> Point { + let eligible = |p| hit_anchor(cx, p, 0.0).is_some() || hit_segment(cx, p, cx.pick_tol()).is_some(); + let fallback = (cx.smart_guides || cx.snap_to_point) + && !cx.snaps_to_pixel(PixelOp::Drawing) + && !cx.snap_to_grid + && snapped != raw + && !eligible(snapped) + && eligible(raw); + let snapped = if fallback { + self.scissors_snap.clear(); + raw + } else { + snapped + }; + self.scissors_hover = + Some(ScissorsHover { raw, snapped, zoom: cx.zoom, isolation: cx.isolation, selection_tolerance: cx.selection_tolerance }); + snapped + } + + /// Prefer a path actually at the snapped point before a nearby selected path. The small + /// tolerance covers curve-meeting roundoff. Pixel, grid and alignment points can lie off all + /// paths; there the ordinary full pick radius keeps the existing selected-path priority. + fn scissors_segment(cx: &ToolContext, p: Point) -> Option<(NodeId, usize, usize, f64)> { + let tol = cx.pick_tol(); + if cx.smart_guides || cx.snap_to_point || cx.snaps_to_pixel(PixelOp::Drawing) || cx.snap_to_grid { + super::segment_in(cx, super::candidate_paths(cx), p, tol.min(1e-6)).or_else(|| hit_segment(cx, p, tol)) + } else { + hit_segment(cx, p, tol) + } + } + + fn scissors_press(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + let p = ev.pos; + if ev.mods.alt { + return Self::add(cx, p); + } + let snapped = self.scissors_snap.press(cx, p, &[], None); + let p = self.resolve_scissors_snap(cx, p, snapped); + let point = cx.point_tol(); + // A path snap must not be pulled to a nearby anchor by the larger pick radius. + // Shared anchor targets and the path's anchors use the same stored coordinates. + let snapping = cx.smart_guides || cx.snap_to_point || cx.snaps_to_pixel(PixelOp::Drawing) || cx.snap_to_grid; + let anchor_tol = if snapping { 0.0 } else { point }; + if let Some((id, si, ai)) = hit_anchor(cx, p, anchor_tol) { + return vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))]; + } + match Self::scissors_segment(cx, p) { + Some((id, si, seg, t)) => vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t}))], + None => vec![], + } + } + + /// 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 +277,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 +301,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; @@ -300,7 +409,10 @@ impl Tool for AnchorTool { /// handle, a segment, a blend spine's point, handle or segment) cancels it: what it moved goes /// back and the release does nothing. Escape after a press that has not moved yet drops the /// press, so its release converts nothing. - fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + fn key(&mut self, _cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { + if self.id == "scissors" && (key == ToolKey::Escape || mods.alt) { + self.clear_scissors_snap(); + } if key != ToolKey::Escape || matches!(self.state, State::Idle) { return vec![]; } @@ -322,8 +434,9 @@ impl Tool for AnchorTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; - // Anchors and handle ends are picked from a little further than segments. - let (tol, point) = (cx.pick_tol(), cx.point_tol()); + if self.id == "scissors" && ev.mods.alt { + self.clear_scissors_snap(); + } match (self.id, ev.kind) { ("addAnchor", PointerKind::Down) => { if ev.mods.alt { @@ -339,18 +452,18 @@ impl Tool for AnchorTool { Self::delete(cx, p) } } - ("scissors", PointerKind::Down) => { - if ev.mods.alt { - return Self::add(cx, p); - } - if let Some((id, si, ai)) = hit_anchor(cx, p, point) { - return vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))]; - } - match hit_segment(cx, p, tol) { - Some((id, si, seg, t)) => vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t}))], - None => vec![], + ("scissors", PointerKind::Move) => { + if !ev.mods.alt { + let snapped = self.scissors_snap.hover(cx, p, &[], None); + self.resolve_scissors_snap(cx, p, snapped); } + vec![] } + ("scissors", PointerKind::Up) => { + self.clear_scissors_snap(); + vec![] + } + ("scissors", PointerKind::Down) => self.scissors_press(cx, ev), ("anchorPoint", PointerKind::Down) => { self.space_resume = None; self.state = Self::press_target(cx, p); @@ -458,7 +571,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 +582,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( @@ -549,7 +668,14 @@ impl Tool for AnchorTool { _ => vec![], } } + fn hover_ended(&mut self, _cx: &ToolContext) { + self.clear_scissors_snap(); + } + fn wants_rehover(&self) -> bool { + self.id == "scissors" && self.scissors_hover.is_some() + } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear_scissors_snap(); self.measure = None; let st = std::mem::replace(&mut self.state, State::Idle); match st { @@ -568,6 +694,9 @@ impl Tool for AnchorTool { if matches!(self.state, State::Handle { .. }) { out.extend(self.guides.iter().cloned()); } + if self.id == "scissors" && self.current_scissors_hover(cx).is_some() { + out.extend_from_slice(self.scissors_snap.guides()); + } if cx.measurement_labels && let Some((p, dx, dy)) = self.measure { @@ -583,11 +712,8 @@ impl Tool for AnchorTool { "deleteAnchor" => Cursor::PenAdd, "scissors" if m.alt => Cursor::PenAdd, "scissors" => { - if hit_segment(cx, p, cx.pick_tol()).is_some() { - Cursor::Scissors - } else { - Cursor::ScissorsNotAllowed - } + let p = self.current_scissors_hover(cx).filter(|h| h.raw == p).map_or(p, |h| h.snapped); + if hit_segment(cx, p, cx.pick_tol()).is_some() { Cursor::Scissors } else { Cursor::ScissorsNotAllowed } } _ => match self.state { State::Reshape { .. } => Cursor::ReshapeSegment, diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index 903ae5bea8..ba4bd4df27 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -301,6 +301,317 @@ fn scissors_splits_at_segment() { ); } +fn scissors_crossing() -> (vectorcraft_doc::Document, NodeId, Selection) { + let (mut d, rect) = doc_with_rect(); + let line = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + line, + vectorcraft_geom::shapes::line(Point::new(145.0, 90.0), Point::new(165.0, 130.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + // The selected rectangle is the cut target even though the crossing line is above it. + let mut selected = Selection::default(); + selected.set([rect]); + (d, rect, selected) +} + +fn scissors_cut_at(d: &vectorcraft_doc::Document, id: NodeId, actions: &[Action]) -> Point { + let [Action::Exec(command, args)] = actions else { panic!("expected one split: {actions:?}") }; + assert_eq!(command, "path.split"); + assert_eq!(args["id"], id.0); + let si = args["subpath"].as_u64().unwrap() as usize; + let sp = &d.node(id).unwrap().path_data().unwrap().subpaths[si]; + if let Some(anchor) = args["anchor"].as_u64() { + sp.anchors[anchor as usize].p + } else { + // A straight segment still has cubic parameters: check geometry, not a linear t. + sp.segment(args["segment"].as_u64().unwrap() as usize).eval(args["t"].as_f64().unwrap()) + } +} + +fn scissors_labels(tool: &AnchorTool, cx: &ToolContext) -> Vec<(String, Point)> { + tool.overlays(cx).into_iter().filter_map(|o| if let Overlay::Label { text, p, .. } = o { Some((text, p)) } else { None }).collect() +} + +/// #6470: the hover and the cut use the drawing tools' intersection, with their existing pixel, +/// grid and Smart Guides/Snap to Point precedence. Turning Smart Guides off restores the raw cut. +#[test] +fn scissors_snaps_intersections_with_the_drawing_options() { + let (mut d, rect, selected) = scissors_crossing(); + d.grid = vectorcraft_doc::GridPrefs { spacing: 20.0, subdivisions: 1 }; + let paint = paint(); + for (smart, point, pixel, grid, x, label) in [ + (true, true, false, false, 150.0, Some("intersect")), + (false, false, false, false, 152.0, None), + (false, true, false, false, 152.0, None), + (true, true, true, false, 152.0, None), + (true, true, false, true, 160.0, None), + ] { + let c = ToolContext { smart_guides: smart, snap_to_point: point, snap_to_pixel: pixel, snap_to_grid: grid, ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + assert!(tool.pointer(&c, &PointerEvent::new(PointerKind::Move, 152.0, 101.5)).is_empty()); + let hovered = scissors_labels(&tool, &c); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, 152.0, 101.5)); + let cut = scissors_cut_at(&d, rect, &actions); + assert!(cut.distance(Point::new(x, 100.0)) < 1e-6, "smart={smart}, point={point}, pixel={pixel}, grid={grid}: {cut:?}"); + assert_eq!(hovered, label.map(|s| (s.to_string(), Point::new(x, 100.0))).into_iter().collect::>()); + assert!(tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 152.0, 101.5)).is_empty()); + assert!(tool.overlays(&c).is_empty()); + } +} + +/// Snapping chooses the path it names, rather than a selected path merely within pick tolerance. +/// With every snap off, the existing selected-path priority still applies to the raw pointer. +#[test] +fn scissors_snapped_path_beats_nearby_selected_path() { + let (mut d, rect) = doc_with_rect(); + let line = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + line, + vectorcraft_geom::shapes::line(Point::new(120.0, 102.0), Point::new(240.0, 102.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut selected = Selection::default(); + selected.set([rect]); + let paint = paint(); + for (smart, point, at, owner, target) in [ + (false, false, (150.0, 101.6), rect, (150.0, 100.0)), + (true, true, (150.0, 101.6), line, (150.0, 102.0)), + (false, true, (150.0, 101.6), rect, (150.0, 100.0)), + (false, true, (150.0, 102.0), line, (150.0, 102.0)), + ] { + let (at, target) = (Point::from(at), Point::from(target)); + let c = ToolContext { smart_guides: smart, snap_to_point: point, snap_to_pixel: false, snap_to_grid: false, ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let labels = scissors_labels(&tool, &c); + if smart { + assert_eq!(labels.len(), 1, "{labels:?}"); + assert_eq!(labels[0].0, "path"); + assert!(labels[0].1.distance(Point::new(150.0, 102.0)) < 1e-6, "{labels:?}"); + } else { + assert!(labels.is_empty(), "{labels:?}"); + } + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(scissors_cut_at(&d, owner, &actions).distance(target) < 1e-6, "smart={smart}, point={point}: {actions:?}"); + } +} + +/// Outside art can give an isolated path useful guides, but an unusable art snap must not turn a +/// valid raw cut into a miss. Pixel/grid precedence still forbids falling back to the raw point. +#[test] +fn scissors_keeps_valid_isolated_cuts_when_outside_art_snaps() { + let (mut d, rect) = doc_with_rect(); + let outside = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + outside, + vectorcraft_geom::shapes::line(Point::new(150.0, 103.5), Point::new(350.0, 350.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut selected = Selection::default(); + selected.set([rect]); + let paint = paint(); + let at = Point::new(150.0, 100.0); + for snapping in [false, true] { + let c = ToolContext { + isolation: Some(rect), + smart_guides: snapping, + snap_to_point: snapping, + snap_to_pixel: false, + snap_to_grid: false, + ..cx(&d, &selected, &paint) + }; + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let labels = scissors_labels(&tool, &c); + let cursor = tool.cursor(&c, at, Mods::default()); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(scissors_cut_at(&d, rect, &actions).distance(at) < 1e-6, "snapping={snapping}: {actions:?}"); + assert_eq!(cursor, Cursor::Scissors, "snapping={snapping}"); + assert!(labels.is_empty(), "rejected outside snap must not guide the raw cut: {labels:?}"); + assert!(scissors_labels(&tool, &c).is_empty(), "the press also discards its rejected guide"); + } + + // The same isolation may still use an outside path's intersection on the eligible rectangle. + let (d, rect, selected) = scissors_crossing(); + let c = ToolContext { isolation: Some(rect), ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + let at = Point::new(152.0, 101.5); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let labels = scissors_labels(&tool, &c); + assert_eq!(labels.len(), 1, "{labels:?}"); + assert_eq!(labels[0].0, "intersect"); + assert!(labels[0].1.distance(Point::new(150.0, 100.0)) < 1e-6, "{labels:?}"); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(scissors_cut_at(&d, rect, &actions).distance(Point::new(150.0, 100.0)) < 1e-6, "{actions:?}"); + + // A grid snap away from the path remains a miss even though the raw point is cuttable. + let (mut d, rect) = doc_with_rect(); + d.node_mut(rect).unwrap().transform(vectorcraft_geom::Affine::translate((0.0, 3.5)), true); + d.grid = vectorcraft_doc::GridPrefs { spacing: 20.0, subdivisions: 1 }; + let mut selected = Selection::default(); + selected.set([rect]); + let c = ToolContext { isolation: Some(rect), snap_to_grid: true, ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + let at = Point::new(150.0, 103.5); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + assert!(tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty()); + assert!(scissors_labels(&tool, &c).is_empty()); +} + +/// Path and alignment labels use the same targets as the Pen. A configured snap reach beyond the +/// anchor's pick radius proves that snapping chooses the anchor rather than a nearby segment. +#[test] +fn scissors_shows_paths_alignment_and_configured_anchor_snaps() { + let (d, rect) = doc_with_rect(); + let (selected, paint) = (Selection::default(), paint()); + for (at, smart, point, reach, label, target, cuts) in [ + ((170.0, 201.0), true, true, 4.0, Some("path"), (170.0, 200.0), true), + ((151.5, 431.0), true, true, 4.0, Some("align"), (150.0, 431.0), false), + ((201.0, 105.5), true, true, 8.0, Some("anchor"), (200.0, 100.0), true), + ((201.0, 105.5), true, true, 4.0, Some("path"), (200.0, 105.5), true), + // Snap to Point keeps the anchor target without Smart Guides labels. + ((201.0, 105.5), false, true, 8.0, None, (200.0, 100.0), true), + // Outside Smart Guides' reach, but inside the legacy 4.5 px anchor pick radius. + ((200.0, 104.25), true, true, 4.0, Some("path"), (200.0, 104.25), true), + ((200.0, 104.25), false, false, 4.0, None, (200.0, 100.0), true), + ] { + let c = + ToolContext { smart_guides: smart, snap_to_point: point, snapping_tolerance: reach, snap_tolerance: reach, ..cx(&d, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.0, at.1)); + let target = Point::from(target); + let labels = scissors_labels(&tool, &c); + if let Some(label) = label { + assert_eq!(labels.len(), 1, "at={at:?}, smart={smart}, point={point}, reach={reach}, want={label}: {labels:?}"); + assert_eq!(labels[0].0, label); + assert!(labels[0].1.distance(target) < 1e-6, "{labels:?}"); + } else { + assert!(labels.is_empty(), "{labels:?}"); + } + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.0, at.1)); + if cuts { + assert!(scissors_cut_at(&d, rect, &actions).distance(target) < 1e-6, "{actions:?}"); + if target == Point::new(200.0, 100.0) { + assert!(matches!(&actions[..], [Action::Exec(_, v)] if v["anchor"] == 1)); + } + } else { + assert!(actions.is_empty(), "a guide away from every path must not cut: {actions:?}"); + } + } +} + +/// A cached snap is for the same raw position, document state and drawing options only. A press +/// gathers fresh targets, even when a previous hover's document state is reused by a caller. +#[test] +fn scissors_cursor_and_press_use_current_snaps() { + let (d, rect) = doc_with_rect(); + let (selected, paint) = (Selection::default(), paint()); + let mut c = cx(&d, &selected, &paint); + let mut tool = AnchorTool::new("scissors"); + let at = Point::new(204.0, 140.0); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + assert_eq!(tool.cursor(&c, Point::new(204.0, 160.0), Mods::default()), Cursor::ScissorsNotAllowed); + assert!(!tool.overlays(&c).is_empty()); + // These interaction inputs can change without a document revision. The old hover must not + // keep moving the cursor onto the path or showing guides until another pointer move. + c.selection_tolerance = 1.0; + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + assert!(tool.overlays(&c).is_empty()); + c.selection_tolerance = 3.0; + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + assert!(!tool.overlays(&c).is_empty()); + c.isolation = Some(rect); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + assert!(tool.overlays(&c).is_empty()); + c.isolation = None; + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::Scissors); + assert!(!tool.overlays(&c).is_empty()); + c.smart_guides = false; + c.snap_to_point = false; + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + assert!(tool.overlays(&c).is_empty()); + c.smart_guides = true; + c.snap_to_point = true; + c.zoom = 2.0; + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + c.zoom = 1.0; + c.revision.1 += 1; + assert_eq!(tool.cursor(&c, at, Mods::default()), Cursor::ScissorsNotAllowed); + + let (crossing, _, selected) = scissors_crossing(); + let before = cx(&crossing, &selected, &paint); + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&before, &PointerEvent::new(PointerKind::Move, 152.0, 101.5)); + let after = cx(&d, &selected, &paint); + let actions = tool.pointer(&after, &PointerEvent::new(PointerKind::Down, 152.0, 101.5)); + assert!(scissors_cut_at(&d, rect, &actions).distance(Point::new(152.0, 100.0)) < 1e-6, "{actions:?}"); +} + +/// Ending the hover, release, Escape (including a dropped touch) and switching tools drop both the +/// guides and the cursor's snap. Alt lends the raw Add Anchor Point tool, with no Scissors guide. +#[test] +fn scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over() { + let (d, _) = doc_with_rect(); + let (selected, paint) = (Selection::default(), paint()); + let c = cx(&d, &selected, &paint); + for ending in 0..7 { + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, 204.0, 140.0)); + assert!(!tool.overlays(&c).is_empty()); + match ending { + 0 => { + tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 204.0, 140.0)); + } + 1 => { + tool.key(&c, ToolKey::Escape, Mods::default()); + } + 2 => { + tool.drop_press(&c); + } + 3 => { + tool.deactivate(&c); + } + 4 => tool.hover_ended(&c), + _ => { + let alt = Mods { alt: true, ..Mods::default() }; + let kind = if ending == 5 { PointerKind::Move } else { PointerKind::Down }; + let event = PointerEvent::new(kind, 170.0, 201.0); + let mut add = AnchorTool::new("addAnchor"); + let actions = tool.pointer(&c, &event.with_mods(alt)); + assert_eq!(actions, add.pointer(&c, &event)); + if kind == PointerKind::Down { + assert!(matches!(&actions[..], [Action::Exec(command, _)] if command == "path.insertAnchor")); + } + assert_eq!(tool.cursor(&c, event.pos, alt), Cursor::PenAdd); + } + } + assert!(tool.overlays(&c).is_empty(), "ending {ending}"); + assert_eq!(tool.cursor(&c, Point::new(204.0, 140.0), Mods::default()), Cursor::ScissorsNotAllowed, "ending {ending}"); + } +} + /// With Alt held the Scissors tool acts as the Add Anchor Point tool: a click sends what the Add /// Anchor Point tool's click sends (an anchor inserted on a segment, nothing away from every path) /// and never splits, and the cursor is the Add Anchor Point tool's everywhere. Without Alt it cuts @@ -610,3 +921,131 @@ 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 { .. }))); } + +/// Disabled Drawing pixel snapping must behave like the same effective art-snap mode. +/// Drawing enabled is the ordinary pixel-priority control at this integer cut point. +#[test] +fn scissors_drawing_pixel_option_keeps_valid_isolated_cuts() { + let (mut d, rect) = doc_with_rect(); + let outside = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + outside, + vectorcraft_geom::shapes::line(Point::new(150.0, 103.5), Point::new(350.0, 350.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut selected = Selection::default(); + selected.set([rect]); + let paint = paint(); + let at = Point::new(150.0, 100.0); + for drawing in [true, false] { + let c = ToolContext { + isolation: Some(rect), + smart_guides: true, + snap_to_point: true, + snap_to_pixel: true, + pixel_snap: crate::PixelSnap { drawing, ..Default::default() }, + snap_to_grid: false, + ..cx(&d, &selected, &paint) + }; + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let labels = scissors_labels(&tool, &c); + let cursor = tool.cursor(&c, at, Mods::default()); + let actions = tool.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(!actions.is_empty(), "drawing={drawing}: expected a valid isolated cut"); + assert!(scissors_cut_at(&d, rect, &actions).distance(at) < 1e-6, "drawing={drawing}: {actions:?}"); + assert_eq!(cursor, Cursor::Scissors, "drawing={drawing}"); + assert!(labels.is_empty(), "rejected outside snap must not guide the raw cut: {labels:?}"); + assert!(scissors_labels(&tool, &c).is_empty(), "the press also discards its rejected guide"); + } +} + +/// 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..ba5e8afe9c 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -10,8 +10,9 @@ //! Guides and Snap to Point: it shows no Smart Guides, hovering or drawing, and its ends follow the //! hand. Snap to Grid and Snap to Pixel still move its ends (`grid_snaps`). The Paintbrush records the pen pressure of each point (a stroke a pen //! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and -//! the pen's tilt and barrel rotation where the pen reads them (`[x, y, pressure, tiltX, tiltY, -//! rotation]` points, `null` for what a point lacks) for brushes that vary with them. The Blob +//! the pen's tilt, barrel rotation and airbrush finger wheel where the pen reads them (`[x, y, +//! pressure, tiltX, tiltY, rotation, wheel]` points, `null` for what a point lacks) for brushes +//! that vary with them. The Blob //! Brush and Eraser also record pressure when their Size varies with Pressure, and the Eraser //! records the pressure, tilt and rotation that its Angle, Roundness and Size variations follow; //! while it erases, its tip outline at the pointer takes the angle, roundness and size the pen @@ -37,7 +38,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; @@ -104,8 +105,8 @@ pub struct GestureTool { /// The pen pressure of each of `points` (the Paintbrush, the Blob Brush with Size on Pressure, /// and the Eraser with any of its variations on Pressure). pressures: Vec, - /// The pen's tilt and rotation at each of `points` (the Paintbrush, and the Eraser with any of - /// its variations on Tilt, Bearing or Rotation). + /// The pen's tilt, rotation and wheel at each of `points` (the Paintbrush, and the Eraser with + /// any of its variations on Tilt, Bearing or Rotation). poses: Vec>, active: bool, began: bool, @@ -200,6 +201,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 +906,8 @@ impl GestureTool { snap: DrawSnap::default(), pressed: Point::ZERO, tip_at: None, + tip_alt: false, + bristle_pen: None, light: false, bearing: None, bearings: vec![], @@ -954,7 +963,8 @@ impl GestureTool { self.id != "pencil" || self.live_preview } - /// Add a stroke sample, with the pen's pressure, tilt and rotation of the event `ev` there. + /// Add a stroke sample, with the pen's pressure, tilt, rotation and wheel of the event `ev` + /// there. fn push(&mut self, p: Point, ev: &PointerEvent) { if let Some(last) = self.points.last() { self.length += last.distance(p); @@ -962,7 +972,8 @@ impl GestureTool { self.points.push(p); let modes = self.tip_modes(); // The poses go out beside the pressures (`stroke_json`), so a stroke that keeps one keeps both. - let posed = self.id == "paintbrush" || modes.iter().any(|m| matches!(m, Variation::Tilt | Variation::Bearing | Variation::Rotation)); + let posed = self.id == "paintbrush" + || modes.iter().any(|m| matches!(m, Variation::Tilt | Variation::Bearing | Variation::Rotation | Variation::StylusWheel)); if posed || modes.contains(&Variation::Pressure) { self.pressures.push(ev.pressure); self.light |= ev.pressure < 1.0; @@ -1088,12 +1099,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; @@ -1228,6 +1277,7 @@ impl GestureTool { Variation::Tilt => posed && self.poses.iter().flatten().any(|q| q.tilt.is_some()), Variation::Bearing => posed && self.bearings.iter().any(Option::is_some), Variation::Rotation => posed && self.poses.iter().flatten().any(|q| q.rotation.is_some()), + Variation::StylusWheel => posed && self.poses.iter().flatten().any(|q| q.wheel.is_some()), Variation::Fixed | Variation::Random => false, }; if self.smoothing { @@ -1268,7 +1318,7 @@ impl GestureTool { let (a, b) = ((a - 0.5) * 360.0, (b - 0.5) * 360.0); 0.5 + vectorcraft_geom::normalize_deg(a + vectorcraft_geom::normalize_deg(b - a) / 2.0) / 360.0 }; - self.tip_of_controls([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, turn(a[2], b[2]), turn(a[3], b[3])]) + self.tip_of_controls([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, turn(a[2], b[2]), turn(a[3], b[3]), (a[4] + b[4]) / 2.0]) } /// What each of the variation modes Pressure, Tilt, Bearing and Rotation reads at point `i` of @@ -1277,7 +1327,7 @@ impl GestureTool { /// the bearing of the last point up to it that the pen leaned 1° or more at, or before the /// first such point the bearing of that first one. What the release does not read /// ([`Self::reads_pressures`], [`Self::reads_poses`]) reads ½, the values themselves. - fn controls_of_point(&self, i: usize) -> [f64; 4] { + fn controls_of_point(&self, i: usize) -> [f64; 5] { let pressure = if self.reads_pressures() { self.pressures.get(i).map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; let (pose, bearing) = if self.reads_poses() { (self.poses.get(i).copied().flatten(), self.bearings.get(i).copied().flatten().or(self.first_bearing)) @@ -1306,7 +1356,7 @@ impl GestureTool { /// The Eraser's angle, roundness and size where its tip outline shows: while it erases, each /// value on a mode that follows the pen goes from the value less its Variation to the value /// plus it as the pen reads now (the pressure once the pen has pressed less than fully, the - /// tilt and rotation of the last point, and the bearing of the last point the pen leaned 1° or + /// tilt, rotation and wheel of the last point, and the bearing of the last point the pen leaned 1° or /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a /// pen that gives no reading, the values themselves. The Blob Brush's are its own values. fn tip_now(&self) -> [f64; 3] { @@ -1327,7 +1377,7 @@ impl GestureTool { /// The tip's angle, roundness and size where the modes Pressure, Tilt, Bearing and Rotation /// read `controls` (0..1 each, [`super::pen_controls`]). - fn tip_of_controls(&self, controls: [f64; 4]) -> [f64; 3] { + fn tip_of_controls(&self, controls: [f64; 5]) -> [f64; 3] { let base = [self.angle, self.roundness, self.size]; let variations = [self.angle_variation, self.roundness_variation, self.size_variation]; let mut out = base; @@ -1337,6 +1387,7 @@ impl GestureTool { Variation::Tilt => controls[1], Variation::Bearing => controls[2], Variation::Rotation => controls[3], + Variation::StylusWheel => controls[4], Variation::Fixed | Variation::Random => continue, }; // The size goes past a nib's 1296 pt, as `path.eraseRegion` sweeps it. @@ -1346,20 +1397,28 @@ impl GestureTool { [angle, roundness.clamp(1.0, 100.0), size.max(super::MIN_BRUSH_SIZE)] } - /// The stroke's points: `[x, y, pressure, tiltX, tiltY, rotation]` when a pen read its tilt or - /// rotation anywhere along it (`null` for what a point lacks, and for the pressure of a stroke + /// The stroke's points: `[x, y, pressure, tiltX, tiltY, rotation, wheel]` when a pen read its + /// wheel anywhere along it, else `[x, y, pressure, tiltX, tiltY, rotation]` when it read its + /// tilt or rotation anywhere (`null` for what a point lacks, and for the pressure of a stroke /// pressed fully all along), else `[x, y, pressure]` when a pen pressed less than fully /// anywhere (a mouse always presses fully), else `[x, y]`. fn stroke_json(&self) -> Value { let n = self.points.len(); let pressed = self.pressures.len() == n && self.pressures.iter().any(|p| *p < 1.0); - let posed = self.poses.len() == n && self.poses.iter().flatten().any(|q| q.tilt.is_some() || q.rotation.is_some()); + let poses = || self.poses.iter().flatten(); + let wheeled = self.poses.len() == n && poses().any(|q| q.wheel.is_some()); + let posed = wheeled || (self.poses.len() == n && poses().any(|q| q.tilt.is_some() || q.rotation.is_some())); let round = |v: f32, k: f64| (f64::from(v) * k).round() / k; if posed { let points = self.points.iter().zip(&self.pressures).zip(&self.poses).map(|((p, f), q)| { let q = q.unwrap_or_default(); let (tilt, rotation) = (q.tilt.map(|t| t.map(|v| round(v, 100.0))), q.rotation.map(|r| round(r, 100.0))); - json!([p.x, p.y, pressed.then(|| round(*f, 1000.0)), tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation]) + let pressure = pressed.then(|| round(*f, 1000.0)); + if wheeled { + json!([p.x, p.y, pressure, tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation, q.wheel.map(|w| round(w, 1000.0))]) + } else { + json!([p.x, p.y, pressure, tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation]) + } }); Value::Array(points.collect()) } else if pressed { @@ -1587,9 +1646,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 +1819,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 +2120,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..87d18ca4b4 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -124,7 +124,7 @@ fn paintbrush_sends_pen_tilt_and_rotation() { let Some(Action::Preview(_, v)) = last.first() else { panic!("{last:?}") }; v["points"].clone() }; - let leaning = |x: f32, r: Option| Some(PenPose { tilt: Some([x, -10.0]), rotation: r }); + let leaning = |x: f32, r: Option| Some(PenPose { tilt: Some([x, -10.0]), rotation: r, wheel: None }); assert_eq!( stroke("paintbrush", 0.5, [leaning(30.0, Some(45.0)), leaning(40.0, Some(-90.0)), None]), json!([[0.0, 0.0, 0.5, 30.0, -10.0, 45.0], [40.0, 0.0, 0.5, 40.0, -10.0, 270.0], [80.0, 0.0, 0.5, null, null, null]]) @@ -134,6 +134,12 @@ fn paintbrush_sends_pen_tilt_and_rotation() { // A pose that reads nothing is a mouse's. assert_eq!(stroke("paintbrush", 1.0, [Some(PenPose::default()); 3]), json!([[0.0, 0.0], [40.0, 0.0], [80.0, 0.0]])); assert_eq!(stroke("pencil", 0.5, [leaning(30.0, Some(45.0)); 3]), json!([[0.0, 0.0], [40.0, 0.0], [80.0, 0.0]])); + // An airbrush pen's finger wheel comes seventh, and a point without it sends null. + let wheel = |w: f32| Some(PenPose { wheel: Some(w), ..PenPose::default() }); + assert_eq!( + stroke("paintbrush", 1.0, [wheel(0.0), wheel(0.25), None]), + json!([[0.0, 0.0, null, null, null, null, 0.0], [40.0, 0.0, null, null, null, null, 0.25], [80.0, 0.0, null, null, null, null, null]]) + ); } #[test] @@ -3043,6 +3049,105 @@ 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, wheel: None }), + ..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 +3192,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`, `stylusWheel`"; + 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)); @@ -3097,7 +3216,7 @@ fn the_eraser_tip_follows_its_variation_modes() { near(tip(&t), (90.0, 47.5, 110.0, 52.5)); // Erasing with the barrel turned half way round and the pen upright, the tip stands upright and // is 28 by 7 pt; Random leaves the roundness as set. - let pen = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(180.0) }); + let pen = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(180.0), wheel: None }); t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (196.5, 36.0, 203.5, 64.0)); @@ -3134,6 +3253,43 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(b.options()["sizeMode"], json!("pressure")); } +/// An Eraser value on Stylus Wheel follows the wheel the pen recorded, in the tip outline while it +/// erases and in the points the release sends; a pen that gives no wheel reads half way, the value +/// itself. +#[test] +fn the_eraser_tip_follows_the_stylus_wheel() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let tip = |t: &GestureTool| match &t.overlays(&cx)[..] { + [.., Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => vectorcraft_geom::Shape::bounding_box(path), + o => panic!("{o:?}"), + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("stylusWheel")), ("angleVariation", json!(90))] { + t.set_option(k, &v); + } + assert_eq!(t.options()["angleMode"], json!("stylusWheel")); + // The wheel at the far end of its travel turns the 20 by 5 pt tip upright. + let wheel = |w: Option| Some(PenPose { tilt: None, rotation: None, wheel: w }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (197.5, 40.0, 202.5, 60.0)); + let acts = t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!((c.as_str(), &v["angleMode"]), ("path.eraseRegion", &json!("stylusWheel"))); + assert_eq!(v["points"], json!([[100.0, 50.0, null, null, null, null, 1.0], [200.0, 50.0, null, null, null, null, 1.0]])); + // A pen without a wheel keeps the tip lying level. + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (190.0, 47.5, 210.0, 52.5)); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); +} + /// The Eraser's tip outline follows a pen turned in place, which adds no stroke point, and the /// release erases with that reading; and its size passes 1296 pt as `path.eraseRegion` sweeps it. #[test] @@ -3153,8 +3309,8 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("rotation")), ("angleVariation", json!(90))] { t.set_option(k, &v); } - let level = Some(PenPose { tilt: None, rotation: Some(0.0) }); - let turned = Some(PenPose { tilt: None, rotation: Some(180.0) }); + let level = Some(PenPose { tilt: None, rotation: Some(0.0), wheel: None }); + let turned = Some(PenPose { tilt: None, rotation: Some(180.0), wheel: None }); t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (190.0, 47.5, 210.0, 52.5)); @@ -3179,8 +3335,8 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { // With Angle on Bearing, a pen that leaned only at the last point and stands up there again // leaves no bearing: the tip lies level, as set. t.set_option("angleMode", &json!("bearing")); - let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); - let leaning = Some(PenPose { tilt: Some([0.0, 45.0]), rotation: None }); + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None, wheel: None }); + let leaning = Some(PenPose { tilt: Some([0.0, 45.0]), rotation: None, wheel: None }); t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); t.pointer(&cx, &PointerEvent { pen: leaning, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); assert!(tip(&t).height() > 6.0, "{:?}", tip(&t)); @@ -3192,7 +3348,7 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { for (k, v) in [("size", json!(1000)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(1000))] { t.set_option(k, &v); } - let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None, wheel: None }); t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (-800.0, -950.0, 1200.0, 1050.0)); @@ -3228,9 +3384,9 @@ fn the_eraser_drag_area_follows_its_variation_modes() { t.set_option(k, v); } }; - let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); - let turned = Some(PenPose { tilt: None, rotation: Some(180.0) }); - let level = Some(PenPose { tilt: None, rotation: Some(0.0) }); + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None, wheel: None }); + let turned = Some(PenPose { tilt: None, rotation: Some(180.0), wheel: None }); + let level = Some(PenPose { tilt: None, rotation: Some(0.0), wheel: None }); let press = |t: &mut GestureTool, pen: Option, kind: PointerKind, x: f64| { t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(kind, x, 150.0) }); }; @@ -3269,7 +3425,7 @@ fn the_eraser_drag_area_follows_its_variation_modes() { // lying flat the tip is 25% round and stands upright. let mut t = GestureTool::new("eraser"); set(&mut t, &[("size", json!(20)), ("angle", json!(90)), ("roundnessMode", json!("tilt")), ("roundnessVariation", json!(75))]); - let flat = Some(PenPose { tilt: Some([90.0, 0.0]), rotation: None }); + let flat = Some(PenPose { tilt: Some([90.0, 0.0]), rotation: None, wheel: None }); press(&mut t, flat, PointerKind::Down, 50.0); press(&mut t, flat, PointerKind::Drag, 150.0); near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); @@ -3319,8 +3475,8 @@ fn the_eraser_drag_area_matches_the_release_when_pressure_or_a_mode_starts_durin let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); }; - let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); - let leaning = Some(PenPose { tilt: Some([45.0, 0.0]), rotation: None }); + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None, wheel: None }); + let leaning = Some(PenPose { tilt: Some([45.0, 0.0]), rotation: None, wheel: None }); let press = |t: &mut GestureTool, pen: Option, pressure: f32, kind: PointerKind, x: f64| { t.pointer(&cx, &PointerEvent { pen, pressure, ..PointerEvent::new(kind, x, 150.0) }); }; @@ -3410,14 +3566,14 @@ fn the_eraser_drag_area_gives_the_first_lean_to_the_points_before_it() { let mut shown = vec![]; for (i, (tilt, x)) in poses.into_iter().zip([50.0, 100.0, 150.0, 200.0, 250.0]).enumerate() { let kind = if i == 0 { PointerKind::Down } else { PointerKind::Drag }; - let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0) }); + let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0), wheel: None }); t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(kind, x, 150.0) }); if i > 0 { shown.push(bounds(&t)); } } if let Some(tilt) = in_place { - let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0) }); + let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0), wheel: None }); t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 250.2, 150.0) }); shown.push(bounds(&t)); } 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/guides/snap.rs b/crates/tools/src/guides/snap.rs index 496ad00bfb..de09341bc7 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -384,6 +384,12 @@ pub(super) fn visible(cx: &ToolContext) -> Option { } impl DrawSnap { + /// Whether the last hover or press still has the current targets, without gathering the art + /// again. A caller caching the snapped point can use this before reusing it for a cursor. + pub(crate) fn is_current(&self, cx: &ToolContext, exclude: &[NodeId]) -> bool { + self.targets.as_ref().is_some_and(|(key, _)| key.as_ref() == Some(&SnapKey::of(cx, exclude))) + } + /// Snap the pointer hovering at `p` (the art but `exclude` as targets, the anchors of /// `exclude` still pulling), reusing the targets while nothing they depend on changed. pub fn hover(&mut self, cx: &ToolContext, p: Point, exclude: &[NodeId], from: Option<&Leave>) -> Point { diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 5362147b97..80c857abe6 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -46,8 +46,8 @@ pub struct PointerEvent { pub backquote: bool, #[serde(default = "one")] pub pressure: f32, - /// The pen's tilt and barrel rotation, when the pointer is a pen that reads either (a mouse: - /// `None`). + /// The pen's tilt, barrel rotation and finger wheel, when the pointer is a pen that reads any of + /// them (a mouse: `None`). #[serde(default, skip_serializing_if = "Option::is_none")] pub pen: Option, } @@ -58,23 +58,27 @@ fn one() -> f32 { /// How a pen is held, as far as it reads it. Tilt is in degrees, each −90..90 as Pointer Events /// give it, in document axes: `[x, y]`, x positive when the pen leans to the right and y positive -/// when it leans down the page. Rotation is the barrel's, in degrees clockwise (0..360). +/// when it leans down the page. Rotation is the barrel's, in degrees clockwise (0..360). The wheel +/// is where an airbrush pen's finger wheel is set, 0..1 from one end of its travel to the other. #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PenPose { #[serde(default, skip_serializing_if = "Option::is_none")] pub tilt: Option<[f32; 2]>, #[serde(default, skip_serializing_if = "Option::is_none")] pub rotation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wheel: Option, } impl PenPose { - /// Within its ranges: each tilt is clamped to −90..90 and the rotation brought into 0..360; a - /// tilt or rotation that is not a number is left out. + /// Within its ranges: each tilt is clamped to −90..90, the rotation brought into 0..360 and the + /// wheel clamped to 0..1; a tilt, rotation or wheel that is not a number is left out. pub fn sanitized(self) -> Self { let tilt = self.tilt.filter(|t| t.iter().all(|v| v.is_finite())).map(|t| t.map(|v| v.clamp(-90.0, 90.0))); // `rem_euclid` can round a tiny negative angle up to 360 itself. let rotation = self.rotation.filter(|r| r.is_finite()).map(|r| r.rem_euclid(360.0)).map(|r| if r >= 360.0 { 0.0 } else { r }); - Self { tilt, rotation } + let wheel = self.wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0)); + Self { tilt, rotation, wheel } } } @@ -92,14 +96,15 @@ impl PointerEvent { } /// The pen's tilt and rotation of a pointer event given as JSON (control channel, MCP): /// `tiltX` and `tiltY` (degrees, −90..90, in document axes; one without the other is 0) and - /// `rotation` (degrees clockwise, brought into 0..360). Values that are not numbers are left - /// out; `None` without any. + /// `rotation` (degrees clockwise, brought into 0..360) and `wheel` (an airbrush pen's finger + /// wheel, clamped to 0..1). Values that are not numbers are left out; `None` without any. pub fn json_pen(e: &Value) -> Option { let num = |k: &str| e.get(k).and_then(Value::as_f64).filter(|f| f.is_finite()); let tilt = |v: Option| v.map_or(0.0, |v| v.clamp(-90.0, 90.0) as f32); let (tx, ty) = (num("tiltX"), num("tiltY")); let tilt = (tx.is_some() || ty.is_some()).then(|| [tilt(tx), tilt(ty)]); - let pose = PenPose { tilt, rotation: num("rotation").map(|r| r.rem_euclid(360.0) as f32) }.sanitized(); + let rotation = num("rotation").map(|r| r.rem_euclid(360.0) as f32); + let pose = PenPose { tilt, rotation, wheel: num("wheel").map(|w| w.clamp(0.0, 1.0) as f32) }.sanitized(); (pose != PenPose::default()).then_some(pose) } /// How long the pointer then holds still, in seconds, from a JSON pointer event's `holdMs` @@ -113,11 +118,13 @@ impl PointerEvent { v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned())) } /// Checks the optional keys of a JSON pointer event (control channel, MCP): `pressure`, - /// `holdMs`, `tiltX`, `tiltY` and `rotation` must be numbers, and `space` must be `doc` or - /// `screen`. A key that is absent or null keeps its default. + /// `holdMs`, `tiltX`, `tiltY`, `rotation` and `wheel` must be numbers, and `space` must be + /// `doc` or `screen`. A key that is absent or null keeps its default. pub fn json_check(e: &Value) -> Result<(), String> { let given = |k: &str| e.get(k).filter(|v| !v.is_null()); - if let Some(k) = ["pressure", "holdMs", "tiltX", "tiltY", "rotation"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) { + if let Some(k) = + ["pressure", "holdMs", "tiltX", "tiltY", "rotation", "wheel"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) + { return Err(format!("`{k}` must be a number")); } if given("space").is_some_and(|v| !matches!(v.as_str(), Some("doc" | "screen"))) { @@ -157,13 +164,13 @@ mod tests { use serde_json::json; for ok in [ json!({}), - json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "space": "screen"}), + json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "wheel": 0.25, "space": "screen"}), json!({"pressure": null, "space": null}), json!({"space": "doc"}), ] { assert_eq!(PointerEvent::json_check(&ok), Ok(()), "{ok}"); } - for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation"] { + for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation", "wheel"] { for bad in [json!("1"), json!(true), json!([1])] { assert_eq!(PointerEvent::json_check(&json!({k: bad})), Err(format!("`{k}` must be a number")), "{k}: {bad}"); } @@ -172,6 +179,19 @@ mod tests { assert_eq!(PointerEvent::json_check(&json!({"space": bad})), Err("`space` must be doc or screen".to_owned()), "{bad}"); } } + + #[test] + fn json_pen_reads_the_wheel_within_its_range() { + use serde_json::json; + let wheel = |v: Value| PointerEvent::json_pen(&json!({"wheel": v})).and_then(|q| q.wheel); + assert_eq!(wheel(json!(0.25)), Some(0.25)); + assert_eq!(wheel(json!(-3)), Some(0.0)); + assert_eq!(wheel(json!(7)), Some(1.0)); + assert_eq!(wheel(json!(null)), None); + assert_eq!(PointerEvent::json_pen(&json!({"wheel": 0.5})), Some(PenPose { wheel: Some(0.5), ..PenPose::default() })); + assert_eq!(PenPose { wheel: Some(f32::NAN), ..PenPose::default() }.sanitized(), PenPose::default()); + assert_eq!(PenPose { wheel: Some(1.5), ..PenPose::default() }.sanitized().wheel, Some(1.0)); + } } /// Keys tools care about. @@ -214,8 +234,15 @@ pub enum Action { Exec(String, Value), /// Ask the UI to open a dialog (e.g. click with the Rectangle tool → size dialog). Dialog(String, Value), + /// Ask the UI to show and select a panel (e.g. a double-click on a corner widget with a shape + /// tool → Transform). + Panel(String), /// Switch to another tool (e.g. after placing a text frame). SwitchTool(String), /// Call the tool's `notify` after the preceding actions ran (e.g. to pick up a created object). Notify(String), + /// Show this English message in the status bar (e.g. why a Shape Builder gesture built + /// nothing); an empty message clears the status bar. It changes nothing in the document and + /// records no undo step. + Status(String), } 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 7526717665..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 } @@ -282,7 +301,8 @@ pub trait Tool: Send { vec![] } /// The tool, already active, is chosen again (its toolbar button, its shortcut, `tool.select`). - /// Most tools keep their state; the Blend tool finishes the blend it is adding to. + /// Most tools keep their state; the Blend tool finishes the blend it is adding to, and the Pen + /// ends the path it is drawing. fn chosen_again(&mut self, _cx: &ToolContext) -> Vec { vec![] } @@ -364,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) @@ -658,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 24a21d08ca..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); } @@ -458,6 +474,12 @@ impl Tool for PenTool { _ => vec![], } } + /// Choosing the Pen again (P, its toolbar button, `tool.select`) ends the path being drawn as + /// Escape does: the path stays open, the Pen stays chosen, and the next click starts a new + /// path. With no path being drawn it changes nothing. + fn chosen_again(&mut self, cx: &ToolContext) -> Vec { + self.deactivate(cx) + } /// A dropped press drops only the anchor it was placing, a handle it was dragging or the /// close it was making: the path being drawn goes on with the next click. fn drop_press(&mut self, _cx: &ToolContext) -> Vec { @@ -465,6 +487,7 @@ impl Tool for PenTool { self.first = None; self.handle = None; self.convert = None; + self.vector = None; self.snap.clear(); vec![] } @@ -476,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 { @@ -501,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); } @@ -605,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; @@ -684,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 badb8193a7..7b804685b3 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -570,6 +570,98 @@ fn ending_during_a_pen_gesture_commits_and_clears_it() { } } +/// Choosing the Pen again ends the path being drawn as Escape does, with the rubber band on or off +/// and for a one-anchor path: the preview goes, nothing is added to the document, and the next +/// click starts a new path. Mid-drag it commits the anchor being placed first. With no path being +/// drawn it changes nothing. +#[test] +fn choosing_the_pen_again_ends_the_path() { + let p = paint(); + let created = |acts: &[Action]| matches!(acts, [Action::Begin(_), Action::Preview(c, _)] if c == "path.create"); + let preview = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Path { .. } | Overlay::Measure { .. })); + for pts in [vec![Point::new(100.0, 300.0), Point::new(200.0, 300.0)], vec![Point::new(100.0, 300.0)]] { + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&pts, false)); + for band in [true, false] { + let cx = ToolContext { pen_rubber_band: band, ..cx(&d, &s, &p) }; + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 300.0, 410.0)); + assert!(preview(&t.overlays(&cx)), "band {band}"); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::PenDrawing); + assert!(t.chosen_again(&cx).is_empty(), "nothing to commit"); + assert!(!preview(&t.overlays(&cx)), "band {band}"); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::Pen); + let acts = click(&mut t, &cx, 300.0, 410.0, Mods::default()); + assert!(created(&acts), "{} anchors, band {band}: {acts:?}", pts.len()); + } + // Chosen again (through `tool.select`) while a drag places an anchor: it is committed. + let cx = cx(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 410.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 320.0, 440.0)); + assert_eq!(t.chosen_again(&cx), vec![Action::Commit]); + assert!(!t.busy()); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 320.0, 440.0)).is_empty()); + assert!(created(&click(&mut t, &cx, 300.0, 500.0, Mods::default()))); + } + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false)); + let cx = cx(&d, &s, &p); + let mut t = PenTool::default(); + assert!(t.chosen_again(&cx).is_empty()); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::Pen); +} + +/// Choosing the Pen again while it draws a path inside a compound path ends that path as Escape +/// and Enter do: the compound path is selected, the path is not closed, no undo step is added, +/// and the next click starts a new path. Ending a path outside any compound path sends no +/// selection change. +#[test] +fn choosing_the_pen_again_selects_the_compound_parent_of_the_path_being_drawn() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (a, b, compound) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let open = |x: f64| { + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(x, 300.0), Point::new(x + 100.0, 300.0)], false)) + }; + let path = |id, x| std::sync::Arc::new(vectorcraft_doc::Node::path(id, open(x), vectorcraft_doc::Appearance::default_art())); + let mut node = vectorcraft_doc::Node::new( + compound, + NodeKind::Compound { children: vec![path(a, 10.0), path(b, 300.0)], rule: vectorcraft_geom::FillRule::NonZero }, + ); + node.appearance = vectorcraft_doc::Appearance::default_art().into(); + d.insert(Some(l), 1, node).unwrap(); + let p = paint(); + // The member path alone is the selection while the Pen draws it. + let mut s = Selection::default(); + s.set([a]); + let inside = cx(&d, &s, &p); + // The selection once the engine ran `select.set`: the compound path. + let mut sc = Selection::default(); + sc.set([compound]); + let after = cx(&d, &sc, &p); + let select_compound = vec![Action::Exec("select.set".into(), json!({"ids": [compound.0]}))]; + for key in [None, Some(ToolKey::Escape), Some(ToolKey::Enter)] { + let mut t = PenTool { drawing: true, path: Some(a), subpath: Some(0), ..PenTool::default() }; + assert_eq!(t.cursor(&inside, Point::new(250.0, 450.0), Mods::default()), Cursor::PenDrawing, "{key:?}"); + let acts = match key { + Some(k) => t.key(&inside, k, Mods::default()), + None => t.chosen_again(&inside), + }; + assert_eq!(acts, select_compound, "{key:?}: only the selection changes, with no close and no undo step"); + assert!(!t.busy() && t.active(&after).is_none(), "{key:?}: the path is done"); + assert_eq!(t.cursor(&after, Point::new(250.0, 450.0), Mods::default()), Cursor::Pen, "{key:?}"); + let next = click(&mut t, &after, 250.0, 450.0, Mods::default()); + assert!( + matches!(next.as_slice(), [Action::Begin(_), Action::Preview(c, _)] if c == "path.create"), + "{key:?}: the next click starts a new path: {next:?}" + ); + } + let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false)); + let plain = cx(&d, &s, &p); + let mut t = PenTool { drawing: true, path: Some(id), subpath: Some(0), ..PenTool::default() }; + assert!(t.chosen_again(&plain).is_empty()); + assert!(!t.busy() && t.active(&plain).is_none()); +} + /// #501: a press on the first anchor closes the path, however far the drag then goes: the /// closing preview leaves the path closed (so not one the pen extends), and each move still /// previews the close with the incoming handle mirroring the pointer (Alt keeps the outgoing one @@ -773,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] @@ -970,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 1b2cfa3086..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![], @@ -815,9 +823,20 @@ impl Tool for ShapeTool { vec![Action::Dialog(self.id.into(), args)] } } + // A double-click on a corner widget of the selected live shape shows the Transform + // panel; the tool and the selection stay as they are. + PointerKind::DoubleClick if shows_shape_widgets(self.id) && corners::over_widget(cx, ev.pos, false) => { + vec![Action::Panel("transform".into())] + } _ => 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 { @@ -833,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![], @@ -915,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, @@ -951,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. @@ -1012,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 @@ -1083,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 b8c6f9c647..d52cf374d4 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1309,6 +1309,194 @@ 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 +/// angle-excluded corner widget and a spot off the widgets ask for nothing. +#[test] +fn a_double_click_on_a_corner_widget_shows_the_transform_panel() { + 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 double_click = |t: &mut ShapeTool, c: &ToolContext, at: Point| { + let mut out = vec![]; + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + out.push(t.pointer(c, &PointerEvent::new(kind, at.x, at.y))); + } + out + }; + let panel = vec![Action::Panel("transform".into())]; + let xf = Affine::translate((100.0, 100.0)); + let (d, s) = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(110.0, 110.0); + for id in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + let mut t = ShapeTool::new(id); + let out = double_click(&mut t, &c, at); + assert!(out[..4].iter().all(Vec::is_empty), "{id}: {out:?}"); + assert_eq!(out[4], panel, "{id}"); + assert!(!t.busy() && !t.transforming(), "{id}"); + // Off the widgets, a double-click asks for nothing. + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 300.0, 300.0)).is_empty(), "{id}"); + } + // Line Segment has no shape widgets. + let mut t = ShapeTool::new("lineSegment"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // Show Corner Widget off, or the corner wider than the angle limit: the widget is hidden. + let mut hidden = cx(&d, &s, &p); + hidden.corner_widgets = false; + let mut t = ShapeTool::new("rectangle"); + assert!(t.pointer(&hidden, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + let mut narrow = cx(&d, &s, &p); + narrow.corner_widget_max_angle = 80.0; + assert!(t.pointer(&narrow, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // A live polygon's corner widget asks for the panel too. + let (d, s) = live(LiveShape::Polygon { + radius: 100.0, + sides: 6, + xf: Affine::translate((250.0, 250.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }); + let c = cx(&d, &s, &p); + let w = corners::CornerWidgets::for_tool(&c, false).and_then(|w| w.visible().next()).unwrap(); + let mut t = ShapeTool::new("polygon"); + assert_eq!(double_click(&mut t, &c, w)[4], panel); + // A plain path shows no corner widget to a shape tool. + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let c = cx(&d, &s, &p); + let mut t = ShapeTool::new("rectangle"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // A live ellipse's pie widget, 12 px right of (300, 150), is not a corner widget. + let (d, s) = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let c = cx(&d, &s, &p); + let mut t = ShapeTool::new("ellipse"); + assert!(double_click(&mut t, &c, Point::new(312.0, 150.0)).iter().all(Vec::is_empty)); + assert!(!t.busy()); +} + /// A selected live 100 × 100 rectangle at (100, 100)–(200, 200) with no paint: its centre point /// (Attributes › Show Center) is at (150, 150) and its corners at the box's. fn unfilled_live_rect() -> (vectorcraft_doc::Document, Selection) { @@ -1579,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.rs b/crates/ui-egui/src/addons.rs index ec1207ad46..b22f6cb939 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -16,6 +16,7 @@ pub mod polygonal_lasso; pub mod select; pub mod shapes; pub mod typetools; +pub mod units; use crate::menus::Item; @@ -38,6 +39,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), Item::Sub("Type Tools", typetools::menu()), + Item::Sub("Unit Converter", units::menu()), Item::Sep, ] } 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/addons/units.rs b/crates/ui-egui/src/addons/units.rs new file mode 100644 index 0000000000..8822b70167 --- /dev/null +++ b/crates/ui-egui/src/addons/units.rs @@ -0,0 +1,199 @@ +//! Unit Converter in the interface: its submenu (Object › Plug-ins › Unit Converter), which opens +//! the panel, and the panel. The panel shows one length in every unit of +//! [`Unit::EAST_ASIAN`], one number field each. A value typed in any field (units and arithmetic, +//! as every number field reads them) updates the others as it is typed; text that does not read +//! leaves them as they were. From Selection reads the selection's width and height +//! (`addon.units.selectionSize`), and Width or Height picks which of the two the fields show; the +//! size read is dropped when the document, its selection or the bounds measure changes. Apply gives the selection that +//! width or height through `object.setBounds` as the Transform panel's W or H field does (its +//! reference point, Constrain Width and Height Proportions and Transform Object Only, Pattern +//! Only or Both), as one undo step. Each field's copy button puts its value on the clipboard, with +//! its unit when Copy with Units is on. + +use egui::Ui; +use serde_json::json; +use vectorcraft_doc::{Unit, finite_in_every_unit}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::transform; +use crate::panels::{pstate, set_pstate}; +use crate::widgets; + +/// The panel's id (`window.panel {panel: "unitConverter"}`). +pub const ID: &str = "unitConverter"; +/// The command that measures the selection. +pub const SELECTION_SIZE: &str = "addon.units.selectionSize"; + +/// Where the panel keeps its length and choices (panel state). +const STATE: &str = "unit-converter"; +/// A row (label, field, copy button and two gaps) is 214 pt wide, inside the 240 pt body of the +/// default 260 pt floating panel with room for its scroll bar. +const LABEL_W: f32 = 90.0; +const FIELD_W: f32 = 90.0; + +/// Object › Plug-ins › Unit Converter. +pub fn menu() -> Vec { + vec![Item::Cmd("Unit Converter Panel", "window.panel", json!({ "panel": ID }))] +} + +/// The selection's side the fields show and Apply sets. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +pub(crate) enum Side { + #[default] + Width, + Height, +} + +impl Side { + /// `object.setBounds`'s param for this side. + fn key(self) -> &'static str { + match self { + Side::Width => "width", + Side::Height => "height", + } + } +} + +/// The panel's length and choices. +#[derive(Clone, Default, Debug, PartialEq)] +pub(crate) struct Converter { + /// The length (points), none until one is typed or read from the selection. + pub points: Option, + /// The selection's width and height (points) From Selection last read. + pub size: Option<(f64, f64)>, + /// The active document's uid and revision, and the bounds measure (Use Preview Bounds, + /// glyph bounds), when [`Converter::size`] was read. + pub read_at: Option, + /// Which of them the fields show, and the side Apply sets. + pub side: Side, + /// Copy puts the unit after the number. + pub with_units: bool, +} + +impl Converter { + /// Show `side`: the fields take that side of the size From Selection read, if any. + pub fn pick(&mut self, side: Side) { + self.side = side; + if let Some((w, h)) = self.size { + self.points = Some(if side == Side::Width { w } else { h }); + } + } + + /// A length typed in a field: after From Selection it replaces the side shown, so picking the + /// other side and back keeps it. + pub fn set(&mut self, pt: f64) { + self.points = Some(pt); + if let Some((w, h)) = &mut self.size { + *(if self.side == Side::Width { w } else { h }) = pt; + } + } + + /// Drop the size From Selection read when the active document is no longer the one it was + /// read from or is measured another way (`now`: its uid and revision, which a change to the + /// selection also moves, and the bounds measure). The length the fields show stays. + pub fn follow(&mut self, now: Option) { + if self.size.is_some() && self.read_at != now { + self.size = None; + self.read_at = None; + } + } + + /// What the copy button of the field in `unit` puts on the clipboard. + pub fn copied(&self, unit: Unit) -> Option { + self.points.map(|pt| if self.with_units { unit.format(pt) } else { unit.number(pt) }) + } +} + +/// A document's uid and revision, and the bounds measure. +pub(crate) type ReadAt = (u64, u64, vectorcraft_effects::preview::Measure); + +/// The active document's uid and revision, and the bounds measure. +pub(crate) fn document_now(app: &VectorcraftApp) -> Option { + app.session.active().map(|st| (st.uid, st.revision, app.session.bounds_measure())) +} + +/// From Selection: read the selection's width and height into `st`, and show the side picked. +pub(crate) fn from_selection(app: &mut VectorcraftApp, st: &mut Converter) -> Result<(), String> { + let r = app.run(SELECTION_SIZE, json!({}))?; + if let (Some(w), Some(h)) = (r["width"]["points"].as_f64(), r["height"]["points"].as_f64()) { + st.size = Some((w, h)); + st.read_at = document_now(app); + st.pick(st.side); + } + Ok(()) +} + +/// Apply: give the selection the length as its width or height, as the Transform panel's W or H +/// field does: from its reference point (a symbol instance's registration point with Use +/// Registration Point for Symbol on), with the other side following under Constrain Width and +/// Height Proportions, and with the panel menu's Transform Object Only, Pattern Only or Both. +/// Without a length it does nothing. +pub(crate) fn apply(app: &mut VectorcraftApp, ui: &Ui, st: &Converter) -> Result<(), String> { + let Some(pt) = st.points else { return Ok(()) }; + let reference = app.selection_box().map_or_else(|| transform::reference_index(ui), |b| transform::panel_reference(app, ui, &b).index); + let params = json!({ st.side.key(): pt, "reference": reference, "proportional": transform::proportional(app, ui) }); + let params = transform::with_pattern_switches(app, params); + app.run("object.setBounds", params)?; + Ok(()) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let mut st: Converter = pstate(ui.ctx(), STATE); + st.follow(document_now(app)); + // A number typed without a unit is in its row's unit, so 2 in the Picas row is 2 picas, also + // with Preferences › Units › Numbers Without Units Are Points on; other panels' fields keep it. + let bare_points = widgets::typed_unit(ui.ctx(), Unit::Picas) == Unit::Points; + widgets::set_bare_numbers_are_points(ui.ctx(), false); + for unit in Unit::EAST_ASIAN { + widgets::label_row(ui, unit.label(), LABEL_W, |ui| { + // A length too large to show in one of the units (near the largest number, in Q and + // Ha) leaves the others as they were, as text that does not read does. + if let Some(pt) = widgets::num_field_live(ui, ("unit-converter", unit.key()), st.points, unit, FIELD_W) + && finite_in_every_unit(pt) + { + st.set(pt); + } + // The button's name and tip carry the row's unit ("Copy Millimeters"). + let tip = format!("{} {}", tl!("Copy"), tl!(unit.label())); + let copy = widgets::icon_button_enabled(ui, "copy", &tip, false, st.points.is_some(), 22.0); + if copy.clicked() + && let Some(text) = st.copied(unit) + { + ui.ctx().copy_text(text); + } + }); + } + widgets::set_bare_numbers_are_points(ui.ctx(), bare_points); + if widgets::check(ui, "Copy with Units", st.with_units, true) { + st.with_units = !st.with_units; + } + ui.add_space(6.0); + widgets::subheader(ui, tl!("Selection")); + let selected = app.session.active().is_some_and(|d| !d.selection.is_empty()); + ui.horizontal(|ui| { + for (side, label) in [(Side::Width, "Width"), (Side::Height, "Height")] { + if widgets::radio(ui, label, st.side == side, true) { + st.pick(side); + } + } + }); + ui.horizontal(|ui| { + let read = ui.add_enabled_ui(selected, |ui| widgets::flat_button(ui, tl!("From Selection"), 110.0)).inner; + if read.clicked() + && let Err(e) = from_selection(app, &mut st) + { + app.status(e); + } + let set = ui.add_enabled_ui(selected && st.points.is_some(), |ui| widgets::flat_button(ui, tl!("Apply"), 70.0)).inner; + if set.clicked() + && let Err(e) = apply(app, ui, &st) + { + app.status(e); + } + }); + set_pstate(ui.ctx(), STATE, st); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/units/tests.rs b/crates/ui-egui/src/addons/units/tests.rs new file mode 100644 index 0000000000..3959157032 --- /dev/null +++ b/crates/ui-egui/src/addons/units/tests.rs @@ -0,0 +1,329 @@ +//! Unit Converter's submenu and panel: one field per unit, typing in one updates the others and +//! text that does not read leaves them alone, From Selection reads the selection's size, Apply +//! sets the side picked as one undo step and adds none when nothing changes, and Copy writes the +//! value with or without its unit. + +use egui::{Event, Key, Modifiers, Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_doc::Unit; +use vectorcraft_engine::Session; + +use super::{Converter, ID, STATE, Side, apply, document_now, from_selection, show}; +use crate::panels::{pstate, set_pstate}; +use crate::tests_labels::{painted_text, shapes_text}; +use crate::{VectorcraftApp, menus}; + +/// An app with a selected 72 × 36 pt rectangle. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap(); + app +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// The selection's width and height. +fn size(app: &mut VectorcraftApp) -> (f64, f64) { + let r = app.run("addon.units.selectionSize", json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) +} + +#[test] +fn the_submenu_opens_the_panel() { + let mut app = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Unit Converter"] && e.label == "Unit Converter Panel").expect("listed"); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); +} + +#[test] +fn the_panel_has_a_field_for_every_unit_and_its_buttons() { + let mut app = app(); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, Converter { points: Some(720.0 / 25.4), ..Converter::default() }); + show(app, ui); + }); + for u in Unit::EAST_ASIAN { + assert!(text.lines().any(|l| l == u.label()), "{} in {text}", u.label()); + } + for s in ["10 mm", "1 cm", "0.3937 in", "28.346 pt", "40 Q", "40 H"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + for s in ["Copy with Units", "Selection", "Width", "Height", "From Selection", "Apply"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } +} + +#[test] +fn typing_in_a_field_updates_the_others_and_text_that_does_not_read_leaves_them() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + (pstate::(&ctx, STATE), shapes_text(&out)) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the first field, Points, which selects its text so typing replaces it. + frame(&mut app, vec![tab]); + frame(&mut app, vec![]); + let (st, _) = frame(&mut app, vec![Event::Text("1in/2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 36.0)), "{st:?}"); + let (st, text) = frame(&mut app, vec![]); + assert!(near(st.points.unwrap(), 36.0)); + for s in ["0.5 in", "3 p", "12.7 mm", "1.27 cm"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + // Text that does not read keeps the length the other fields show. + let (st, text) = frame(&mut app, vec![Event::Text("x".into())]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); + assert!(text.lines().any(|l| l == "12.7 mm"), "{text}"); + // So does a length too large to show in Q and Ha. + let select_all = Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }; + frame(&mut app, vec![select_all]); + // 1.7e308 pt: finite in points. + let (st, _) = frame(&mut app, vec![Event::Text(format!("17{}", "0".repeat(307)))]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); +} + +#[test] +fn a_number_typed_without_a_unit_in_the_picas_row_is_in_picas() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // Numbers Without Units Are Points is on (its default), and stays on for other fields. + crate::widgets::set_bare_numbers_are_points(&ctx, true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + pstate::(&ctx, STATE) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the Points field, then the Picas field (the copy buttons are off with no length). + for _ in 0..2 { + frame(&mut app, vec![tab.clone()]); + frame(&mut app, vec![]); + } + let st = frame(&mut app, vec![Event::Text("2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 24.0)), "{st:?}"); + assert_eq!(crate::widgets::typed_unit(&ctx, Unit::Picas), Unit::Points, "other fields still read points"); +} + +#[test] +fn picking_a_side_shows_that_side_of_the_size_read() { + let mut st = Converter { size: Some((72.0, 36.0)), ..Converter::default() }; + st.pick(Side::Height); + assert_eq!((st.side, st.points), (Side::Height, Some(36.0))); + st.pick(Side::Width); + assert_eq!(st.points, Some(72.0)); + // A length typed after From Selection replaces the side shown, and picking the other side and + // back keeps it. + st.set(100.0); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + st.pick(Side::Width); + assert_eq!((st.points, st.size), (Some(100.0), Some((100.0, 36.0)))); + // Before From Selection a side keeps the length typed. + let mut st = Converter::default(); + st.set(5.0); + st.pick(Side::Height); + assert_eq!((st.points, st.size), (Some(5.0), None)); +} + +#[test] +fn copy_writes_the_value_with_or_without_its_unit() { + let mut st = Converter { points: Some(72.0), ..Converter::default() }; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1")); + st.with_units = true; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1 in")); + assert_eq!(st.copied(Unit::Millimeters), Some(Unit::Millimeters.format(72.0))); + assert_eq!(Converter::default().copied(Unit::Points), None, "nothing to copy before a length"); +} + +/// Apply `st` in a frame whose shared reference point (the Transform panel's) is `reference`. +fn apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) { + try_apply_at(app, st, reference).unwrap(); +} + +/// [`apply_at`], with its result. +fn try_apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) -> Result<(), String> { + let ctx = egui::Context::default(); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), reference)); + let mut result = Ok(()); + ctx.run_ui(Default::default(), |ui| result = apply(app, ui, st)).textures_delta.clear(); + result +} + +/// The selection's bounding box. +fn bounds(app: &mut VectorcraftApp) -> vectorcraft_geom::Rect { + app.selection_box().unwrap().rect +} + +#[test] +fn from_selection_reads_the_size_and_apply_sets_the_side_picked() { + let mut app = app(); + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + assert_eq!((st.size, st.points), (Some((72.0, 36.0)), Some(72.0))); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + // Apply: 1 in high, from the centre, as one undo step. + let steps = undo_steps(&app); + st.points = Some(72.0); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 72.0) && near(h, 72.0), "{w} × {h}"); + assert_eq!(undo_steps(&app), steps + 1); + // The same length again changes nothing and adds no step. + apply_at(&mut app, &st, 4); + assert_eq!(undo_steps(&app), steps + 1); + // Without a length Apply does nothing. + apply_at(&mut app, &Converter::default(), 4); + assert_eq!(undo_steps(&app), steps + 1); + // Width, kept at the left edge (reference 3). + let x0 = bounds(&mut app).x0; + let st = Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }; + apply_at(&mut app, &st, 3); + let b = bounds(&mut app); + assert!(near(b.width(), 144.0) && near(b.x0, x0), "{b:?}"); + assert_eq!(undo_steps(&app), steps + 2); +} + +/// Apply follows the Transform panel's W and H fields: Constrain Width and Height Proportions +/// scales the other side too, and Transform Pattern Only leaves the object's size alone. +#[test] +fn apply_follows_the_transform_panels_proportions_and_pattern_choice() { + let mut app = app(); + app.run("prefs.set", json!({"key": "constrainProportions", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "{w} × {h}"); + app.run("prefs.set", json!({"key": "constrainProportions", "value": false})).unwrap(); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "pattern"})).unwrap(); + // The object has no pattern to transform: whether the command reports that or not, the + // object keeps its size. + let _ = try_apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "the object keeps its size: {w} × {h}"); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "both"})).unwrap(); + apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + assert!(near(size(&mut app).0, 10.0)); +} + +/// With Use Registration Point for Symbol on and one symbol instance selected, Apply keeps the +/// symbol's registration point (here its top-left corner) in place, as the Transform panel does, +/// instead of the shared reference point (the centre). +#[test] +fn apply_keeps_a_symbol_instances_registration_point() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap(); + let id = app.run("symbol.new", json!({"name": "Corner", "registration": 0})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("prefs.set", json!({"key": "useRegistrationPointForSymbol", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(160.0), side: Side::Width, ..Converter::default() }, 4); + assert_eq!(bounds(&mut app), vectorcraft_geom::Rect::new(100.0, 50.0, 260.0, 90.0)); +} + +/// The size From Selection read belongs to the selection it was read from: after the selection +/// changes, picking a side keeps the length shown instead of showing the old object's side, and +/// Apply sets that length. +#[test] +fn a_size_read_from_another_selection_is_dropped() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp| { + ctx.run_ui(Default::default(), |ui| show(app, ui)).textures_delta.clear(); + pstate::(&ctx, STATE) + }; + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + set_pstate(&ctx, STATE, st); + // Drawing the panel again with nothing changed keeps it. + assert_eq!(frame(&mut app).size, Some((72.0, 36.0))); + // Another object selected. + app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 20, "height": 50})).unwrap(); + let mut st = frame(&mut app); + assert_eq!((st.size, st.points), (None, Some(72.0)), "{st:?}"); + st.pick(Side::Height); + assert_eq!(st.points, Some(72.0), "not the first object's height"); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 20.0) && near(h, 72.0), "{w} × {h}"); + // So does a change to the document. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); + // And a change to how the selection is measured (Use Preview Bounds), which leaves the + // document as it is. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + st.follow(document_now(&app)); + assert!(st.size.is_some()); + app.run("prefs.set", json!({"key": "usePreviewBounds", "value": true})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); +} + +/// Each row's copy button reads as copying that row's unit, so a screen reader tells the twelve +/// apart, and the fields are named by their rows. +#[test] +fn each_copy_button_and_field_is_named_with_its_unit() { + let mut app = app(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, STATE, Converter { points: Some(72.0), ..Converter::default() }); + ctx.run_ui(Default::default(), |ui| show(&mut app, ui)).textures_delta.clear(); + let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // A label node carries its text as its value. + let label_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + let buttons: Vec = + nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label().map(str::to_string)).collect(); + for u in Unit::EAST_ASIAN { + let name = format!("Copy {}", u.label()); + assert_eq!(buttons.iter().filter(|b| **b == name).count(), 1, "{name} in {buttons:?}"); + // The row fits the 240 pt body of the default 260 pt floating panel, with 10 pt left for + // its scroll bar. + let button = nodes.iter().find(|(_, n)| n.label() == Some(name.as_str())).and_then(|(_, n)| n.bounds()).unwrap(); + assert!(button.x1 <= 230.0, "{name} ends at {}", button.x1); + // The field of the row is labeled by the row's label. + let field = nodes + .iter() + .find(|(_, n)| n.role() != egui::accesskit::Role::Button && n.labelled_by().iter().any(|l| label_of(*l).as_deref() == Some(u.label()))); + assert!(field.is_some(), "a field labeled {}", u.label()); + } +} + +#[test] +fn from_selection_with_nothing_selected_reports_it_and_keeps_the_length() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let mut st = Converter { points: Some(10.0), ..Converter::default() }; + assert!(from_selection(&mut app, &mut st).is_err()); + assert_eq!((st.points, st.size), (Some(10.0), None)); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..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(), @@ -182,6 +186,8 @@ impl VectorcraftApp { automation_roots: None, synthetic_frame: false, pending_plugin_install: None, + script_picked: Vec::new(), + script_picked_left_out: false, pen_end: Default::default(), host_iteration: 0, #[cfg(test)] @@ -192,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(), @@ -354,8 +361,13 @@ impl VectorcraftApp { // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); - if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() { - // A script in `$.sleep` goes on when its time is up; until then the app can idle. + if self.session.script_running() + && !self.session.script_waiting() + && self.session.script_dialog().is_none() + && self.session.script_picker().is_none() + { + // A script in `$.sleep` goes on when its time is up; until then the app can idle. A + // script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), @@ -576,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); @@ -602,10 +615,6 @@ impl VectorcraftApp { if self.ui.toolbar && self.ui.screen_mode < 3 { tools_float::set_window_dock_zone(&ctx, ui.available_rect_before_wrap()); } - if !self.ui.tools_beside_canvas { - // A canvas-edge target left from before the setting was turned off docks nothing. - tools_float::clear_canvas_dock_zone(&ctx); - } // Beside the canvas, docked Tools draws inside the canvas panel (`toolbar::show_beside_canvas`). // So does Tools docked on the right, left of the panels. if self.ui.toolbar && self.ui.screen_mode < 3 && ((!self.ui.tools_beside_canvas && !self.ui.toolbar_right) || self.ui.toolbar_pos.is_some()) { @@ -628,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/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 6c31668533..701c0f5ffc 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -252,9 +252,7 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } - if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") { - self.publish_clipboard(); - } + let copied = r.is_ok() && self.publish_copy(id); self.sync_views(); self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. @@ -262,16 +260,13 @@ impl VectorcraftApp { match &r { Err(e) => self.ui.status = e.clone(), Ok(v) => { - // Image Trace's notes (a large image traces more slowly, or was scaled down). - if id.starts_with("imageTrace.make") - && let Some(w) = v["warnings"].as_array().and_then(|w| w.first()).and_then(Value::as_str) - { - self.ui.status = w.to_string(); + if matches!(id, "imageTrace.make" | "imageTrace.makeAndExpand") { + self.show_trace_notes(v); } // A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link. panels::color_guide::after_command(self, id, ¶ms, v, spot_base); if id == "file.new" { - self.ui.status.clear(); + self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). if v["previewMode"] == "pixel" { self.ui.view.pixel_preview = true; @@ -280,7 +275,7 @@ impl VectorcraftApp { // Choosing a data set, or stepping to one, clears the status bar. The reply's `warning` // below then shows when no object is bound to a variable the data set has a value for. if matches!(id, "dataset.select" | "dataset.next" | "dataset.prev") { - self.ui.status.clear(); + self.status(""); } // A font applied with Character's font menu or Find Font's Change becomes the newest recent font. // Find Font's Change records the family the text now carries (any name of it is stored as its @@ -312,9 +307,42 @@ impl VectorcraftApp { } } } + // The message the Copy or Cut leaves is the one its clipboard formats' notes may replace. + if copied { + self.clipboard_publishing.ran_with_status(&self.ui); + } r } + /// After a Copy or Cut `id` that ran: offer what it copied to other apps + /// ([`Self::publish_clipboard`]) → whether `id` is one. + fn publish_copy(&mut self, id: &str) -> bool { + let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut"); + if copy { + self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut")); + } + copy + } + + /// Image Trace's notes in `reply` (a large image traces more slowly, or was scaled down): the + /// first of them and how many there are, with the rest for the message's hover. A trace that + /// made no paths shows its first note as it is. Without notes, the message an earlier trace's + /// notes left is cleared while nothing has set the status since, and any other message stays. + fn show_trace_notes(&mut self, reply: &Value) { + let notes = io::notes_of(reply); + let left = self.trace_runs.notes_status.take(); + let Some(first) = notes.first() else { + io::clear_notes_left(self, left); + return; + }; + let status = match reply["paths"].as_u64() { + Some(0) => first.clone(), + _ => crate::trace_runs::traced_with_notes(notes.len(), first), + }; + io::show_with_notes(self, status, notes); + self.trace_runs.notes_status = Some((self.ui.status.clone(), self.ui.status_sets)); + } + fn set_command_warning(&mut self, id: &str, warning: &str) { self.ui.status = warning.to_string(); if id != "text.replaceFont" { @@ -484,4 +512,30 @@ impl VectorcraftApp { self.ui.status = s.into(); self.ui.status_sets = self.ui.status_sets.wrapping_add(1); } + + /// Begin the interaction a dialog or a panel previews on. Typing in progress is kept as its own + /// undo step first, and the warning of the preview that keeping it applied shows in the status + /// bar, as it does when a tool's drag begins. On an error no interaction begins, so the caller + /// runs no preview. + pub(crate) fn begin_interaction(&mut self, label: &str) -> Result<(), String> { + let warnings = self.session.begin_interaction_warned(label).map_err(|e| e.to_string())?; + self.show_warnings(warnings); + Ok(()) + } + + /// Keep typing in progress as one undo step and end the Type tool's typing session, with the + /// typing that Real-time Drawing off left unapplied applied first; its warning shows in the + /// status bar. + pub(crate) fn keep_typing(&mut self) -> Result<(), String> { + let warnings = self.session.keep_typing().map_err(|e| e.to_string())?; + self.show_warnings(warnings); + Ok(()) + } + + /// Each warning in the status bar in turn, as the tool's status requests show; the last stays. + fn show_warnings(&mut self, warnings: Vec) { + for w in warnings { + self.status(w); + } + } } 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 70c8834c2d..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}; -pub use panes::Panes; +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}; @@ -175,7 +177,7 @@ enum Drag { }, /// A Selection tool move over a panel or toolbar: the art waits where it last moved on the /// canvas, and the panels get it ([`widgets::PanelDrag::Art`]) if it is released there. Back - /// on the canvas the move goes on, as in Illustrator (#2826). + /// on the canvas the move goes on (#2826). Art, /// Fingers making a touch gesture ([`crate::touch`]): the first one's press does nothing. Gesture, @@ -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); @@ -832,7 +835,7 @@ fn frame_options( // Type › Highlight Substituted Fonts: pink behind text in a substitute font. highlight_substituted_fonts: app.session.prefs.highlight_substituted_fonts, // General › Anti-aliased Artwork: off, edges are hard on screen (raster effects and - // pattern tiles stay smooth), as in Illustrator. + // pattern tiles stay smooth). anti_alias: if app.session.prefs.anti_aliased_artwork { vectorcraft_render::AntiAlias::Art } else { vectorcraft_render::AntiAlias::None }, progressive_placed: true, trace_views: true, 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 68f06c70cc..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 } @@ -423,6 +425,7 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result crate::dialogs::open_tool_dialog(app, &kind, p), + vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel), vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t), vectorcraft_engine::UiRequest::Status(msg) => app.status(msg), vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p), @@ -442,3 +445,11 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result app.status(e.to_string()), } } + +/// Show and select `panel` where it is (`window.panel.activate`): a panel already on show stays on +/// show, and a dock hidden by Tab shows again. +fn activate_panel(app: &mut VectorcraftApp, panel: &str) { + if let Err(e) = app.run("window.panel.activate", serde_json::json!({ "panel": panel })) { + app.status(e); + } +} diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 84adb0d861..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. @@ -432,7 +443,7 @@ pub(super) fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option, s let sy = left.top() + d; clip_left.line_segment([pos2(left.right() - len, sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick)); if let Some(text) = label { - // Vertical labels read top-to-bottom, one digit per line like Illustrator. + // Vertical labels read top-to-bottom, one digit per line. let top = sy + 2.0; if top < filled_to { return; diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index bffab8f06c..c103c4b7ea 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -25,7 +25,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { /// The Home screen's column: welcome, New / Open, Recent Files, Learn, presets and community links. fn home_content(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - // The welcome and the New / Open buttons sit centred, as PhotoCraft's Home screen does (#4684). + // The welcome and the New / Open buttons sit centred (#4684). ui.vertical_centered(|ui| { ui.label(egui::RichText::new(tl!("Welcome to VectorCraft")).font(theme::semibold(26.0)).color(t.text)); ui.add_space(4.0); 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 e6e16ad271..cef27dab18 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -1,5 +1,6 @@ //! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document -//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its +//! area, in a grid, side by side or stacked; the 2-up to 6-up layouts show that many and leave the +//! rest under their tabs ([`Layout`]). The current document's pane is the canvas ([`super::show`]). Each other pane draws its //! document from a render of its own, with its artboards, guides and selected objects, and a press //! in it makes its document the current one. A Selection drag released in it drops the dragged //! artwork into its document ([`crate::document_drag::drop_on_pane`]). Each view Window › New @@ -9,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; @@ -39,9 +40,35 @@ pub struct Panes { pending: HashMap, /// The panes the last frame drew, as (window, pane rect). pub(crate) last: Vec<(Win, egui::Rect)>, + /// The slots of `last`'s windows, in the same order: which windows they were, as document + /// indices shift when a document closes. + last_slots: Vec>, /// 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 { @@ -50,7 +77,9 @@ impl Panes { self.shown.clear(); self.pending.clear(); self.last.clear(); + self.last_slots.clear(); self.fits.clear(); + self.outlines.clear(); } /// Upload `img`, the render `key` describes, for `slot`. @@ -162,37 +191,123 @@ fn render_pane( img } -/// The grid of `n` panes in `area`, filled row by row: as many columns as the square root of `n` -/// rounded up, and as many rows as those columns need. The panes meet edge to edge and cover -/// `area`; the spare cells of the last row stay empty. -pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { - if n == 0 { - return vec![]; +/// How Tile lays out the panes (`window.arrange.tile`'s `layout`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Layout { + /// A grid: as many columns as the square root of the number of panes rounded up. + #[default] + Grid, + /// Side by side in one row, each pane as tall as the document area. + Vertical, + /// Stacked in one column, each pane as wide as the document area. + Horizontal, + /// At most this many panes (2, 3, 4 or 6); the other windows stay under their tabs. + Up(usize), +} + +impl Layout { + /// Each layout with its name in `layout`, in the order the menus list them. + pub(crate) const ALL: [(&'static str, Layout); 7] = [ + ("grid", Layout::Grid), + ("vertical", Layout::Vertical), + ("horizontal", Layout::Horizontal), + ("2up", Layout::Up(2)), + ("3up", Layout::Up(3)), + ("4up", Layout::Up(4)), + ("6up", Layout::Up(6)), + ]; + + /// The layout's name in `layout`. + pub(crate) fn name(self) -> &'static str { + Self::ALL.iter().find(|(_, l)| *l == self).map_or("grid", |(n, _)| n) } + + /// The layout `p`'s `layout` names, the grid without one. Any other value is an error. + pub(crate) fn from_params(p: &serde_json::Value) -> Result { + let key = "layout"; + match p.get(key) { + None => Ok(Layout::Grid), + Some(v) => v + .as_str() + .and_then(|s| Self::ALL.iter().find(|(n, _)| *n == s)) + .map(|(_, l)| *l) + .ok_or_else(|| format!("`{key}` must be one of {}", Self::ALL.map(|(n, _)| n).join(", "))), + } + } + + /// How many of `n` windows the layout gives a pane. + fn panes(self, n: usize) -> usize { + match self { + Layout::Up(k) => n.min(k), + _ => n, + } + } + + /// How many columns the layout puts `n` panes in. + fn columns(self, n: usize) -> usize { + match self { + Layout::Grid => grid_columns(n), + Layout::Vertical => n, + Layout::Horizontal => 1, + Layout::Up(k) if k <= 3 => n, + Layout::Up(k) => grid_columns(k).min(n), + } + } +} + +/// The square root of `n` rounded up. +fn grid_columns(n: usize) -> usize { let mut cols = 1; while cols * cols < n { cols += 1; } + cols +} + +/// The `n` panes `layout` places in `area`, filled row by row, in as many rows as its columns +/// need (the grid: as many columns as the square root of `n` rounded up). The panes meet edge to +/// edge and cover `area`; the spare cells of the last row stay empty. +pub(crate) fn layout_cells(layout: Layout, n: usize, area: egui::Rect) -> Vec { + if n == 0 { + return vec![]; + } + let cols = layout.columns(n).clamp(1, n); let rows = n.div_ceil(cols); let x = |c: usize| if c == cols { area.right() } else { area.left() + area.width() * c as f32 / cols as f32 }; let y = |r: usize| if r == rows { area.bottom() } else { area.top() + area.height() * r as f32 / rows as f32 }; (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own, -/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it -/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it. -pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { +/// The windows of `docked` (in tab order) that `layout` gives a pane: all of them, or as many of +/// the first ones as it shows, with the current window `active` in the last pane when it is not +/// among them. +pub(crate) fn shown_windows(layout: Layout, docked: &[Win], active: Option) -> Vec { + let k = layout.panes(docked.len()); + let mut shown = docked[..k].to_vec(); + if let (Some(a), Some(last)) = (active.filter(|a| !shown.contains(a) && docked.contains(a)), shown.last_mut()) { + *last = a; + } + shown +} + +/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own +/// as `layout` places them (the grid without one), each fitted to its pane. With fewer than two +/// windows open (when the menu item is grayed out) it leaves the view, `tiled` and the layout as +/// they are. The windows floating come back under the tabs for it. A `layout` that is not one of +/// [`Layout::ALL`]'s names is an error. +pub(crate) fn tile(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result { + let layout = Layout::from_params(p)?; app.sync_views(); let n = crate::doc_windows::windows(app).len(); if n < 2 { - return Ok(json!({"tiled": app.ui.tiled, "panes": n})); + return Ok(json!({"tiled": app.ui.tiled, "panes": n, "layout": app.ui.tile_layout.name()})); } crate::doc_windows::dock_all(app); app.ui.tiled = true; + app.ui.tile_layout = layout; app.ui.home = None; crate::doc_windows::unfit_all(app); - Ok(json!({"tiled": app.ui.tiled, "panes": n})) + Ok(json!({"tiled": app.ui.tiled, "panes": layout.panes(n), "layout": layout.name()})) } /// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab, the @@ -220,27 +335,47 @@ 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; } // The current window's pane is the canvas, unless it is a floating one. let active = crate::doc_windows::current(app).filter(|a| docked.contains(a)); + // The 2-up to 6-up layouts leave the windows past their panes under the tabs. + let layout = app.ui.tile_layout; + let shown = shown_windows(layout, &docked, active); app.sync_views(); - let live: Vec = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect(); + // The renders of the panes and the floating windows stay; a window under its tab has none. + let live: Vec = + crate::doc_windows::windows(app).into_iter().filter(|w| shown.contains(w) || !docked.contains(w)).filter_map(|w| slot(app, w)).collect(); 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)); - // A window opened, closed, floated or docked changes the grid, and so does coming back to the - // panes from one window: each window fits its new pane. - if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) { - for w in &docked { - if let Some(v) = crate::doc_windows::view_mut(app, *w) { - v.fitted = false; - } + 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 + // window into the last pane of a 2-up to 6-up layout, or when 6-Up loses its sixth document. + // Windows are compared by their slots, since a closed document shifts the indices of the + // documents after it, and panes by their place in the layout. + let before = std::mem::take(&mut app.canvas.panes.last_slots); + let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); + let unit = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 1.0)); + let (cells_before, cells_now) = (layout_cells(layout, before.len(), unit), layout_cells(layout, now.len(), unit)); + for (i, (w, s)) in shown.iter().zip(&now).enumerate() { + if s.is_some() && before.get(i) == Some(s) && cells_before.get(i) == cells_now.get(i) { + continue; + } + if let Some(v) = crate::doc_windows::view_mut(app, *w) { + v.fitted = false; } } + app.canvas.panes.last_slots = now; let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); + let cells: Vec<(Win, egui::Rect)> = shown.iter().copied().zip(layout_cells(layout, shown.len(), ui.available_rect_before_wrap())).collect(); let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect(); let unfitted = refit_resized(app, &areas); let mut activate = None; @@ -456,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); @@ -474,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 03c0ce7bed..15e5e138d3 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -43,6 +43,11 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event { egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } } +/// Tile's grid of `n` panes in `area`. +fn cells(n: usize, area: egui::Rect) -> Vec { + layout_cells(Layout::Grid, n, area) +} + /// The documents' indices in the panes the last frame drew, and the panes. fn panes(app: &VectorcraftApp) -> (Vec, Vec) { app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip() @@ -84,6 +89,336 @@ fn cells_tile_the_area_edge_to_edge() { } } +/// The distinct left and top edges of `c`: how many columns and rows its panes take. +fn columns_and_rows(c: &[egui::Rect]) -> (usize, usize) { + let lefts: BTreeSet = c.iter().map(|r| r.left().to_bits()).collect(); + let tops: BTreeSet = c.iter().map(|r| r.top().to_bits()).collect(); + (lefts.len(), tops.len()) +} + +#[test] +fn each_tile_layout_places_its_panes_edge_to_edge() { + let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0)); + let cases = [ + (Layout::Vertical, 3, (3, 1)), + (Layout::Vertical, 7, (7, 1)), + (Layout::Horizontal, 3, (1, 3)), + (Layout::Up(2), 2, (2, 1)), + (Layout::Up(3), 3, (3, 1)), + (Layout::Up(3), 2, (2, 1)), + (Layout::Up(4), 4, (2, 2)), + (Layout::Up(4), 3, (2, 2)), + (Layout::Up(6), 6, (3, 2)), + (Layout::Up(6), 4, (3, 2)), + (Layout::Up(6), 2, (2, 1)), + ]; + for (layout, n, shape) in cases { + let c = layout_cells(layout, n, area); + assert_eq!(c.len(), n); + assert_eq!(columns_and_rows(&c), shape, "{layout:?} with {n} panes: columns and rows"); + assert_eq!(c[0].min, area.min, "{layout:?}: the first pane starts at the corner"); + let right = c.iter().map(|r| r.right()).fold(f32::MIN, f32::max); + let bottom = c.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max); + assert_eq!((right, bottom), (area.right(), area.bottom()), "{layout:?} with {n} panes reaches the far edges"); + for (i, r) in c.iter().enumerate() { + assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{layout:?}: {r:?}"); + for o in &c[i + 1..] { + assert!(r.intersect(*o).area() <= 0.0, "{layout:?} panes overlap: {r:?} {o:?}"); + } + } + } + assert!(layout_cells(Layout::Up(2), 0, area).is_empty()); +} + +#[test] +fn tile_layouts_line_the_documents_up_side_by_side_or_stacked() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + let reply = app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "vertical"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].top() == p[1].top() && p[0].height() == p[1].height() && p[0].right() == p[1].left()), "{rects:?}"); + let reply = app.run("window.arrange.tile", json!({"layout": "horizontal"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "horizontal"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].left() == p[1].left() && p[0].width() == p[1].width() && p[0].bottom() == p[1].top()), "{rects:?}"); + // Each document fits its new pane. + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let canvas = app.canvas_rect.unwrap(); + for (i, r) in docs.iter().zip(&rects) { + let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 }; + let v = app.views[*i]; + assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}"); + } + assert_eq!(crate::control::inspect(&app, &ctx)["tileLayout"], json!("horizontal")); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap()["layout"], json!("grid"), "Tile without a layout is the grid"); +} + +#[test] +fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() { + let mut app = app_with(5); + let ctx = egui::Context::default(); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "2up"})); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 4], "the current document takes the last pane"); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1], "the first documents in tab order"); + let second = (app.session.documents()[1].uid, 1); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.shown.contains_key(&second), "the second document is rendered for its pane"); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 3], "a document chosen under its tab comes into the last pane"); + assert!(!app.canvas.panes.shown.contains_key(&second), "a document under its tab keeps no render"); + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let shown = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + assert!((app.views[0].zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9); + assert!(app.canvas_rect.is_some_and(|c| rects[1].contains_rect(c)), "the current document's pane is the canvas"); + // A document brought into the last pane leaves the first pane's zoom as it is. + app.views[0].zoom *= 2.0; + let zoomed = app.views[0].zoom; + app.run("document.activate", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 2]); + assert_eq!(app.views[0].zoom, zoomed, "the document that stayed in its pane keeps its zoom"); + let last = app.canvas_rect.unwrap(); + assert!((app.views[2].zoom - fit_zoom(last, artboard, 0.0, 1.0)).abs() < 1e-9, "the document brought in fits its pane"); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap()["panes"], json!(4)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3], (2, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap()["panes"], json!(5), "6-Up with five documents shows them all"); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "3up"})).unwrap()["panes"], json!(3)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2], (3, 1))); + app.run("document.activate", json!({"index": 4})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 4]); +} + +/// A document closed before the panes shifts the indices of the ones after it: the document that +/// moves into another pane fits it. +#[test] +fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { + let mut app = app_with(4); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 3]); + let moving = app.session.documents()[1].uid; + // The second document's view, under its tab, is zoomed away from its fit. + app.views[1].zoom *= 3.0; + app.run("file.close", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 2], "the former second document is first now, the current one stays last"); + assert_eq!(app.session.documents()[0].uid, moving); + let area = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + let v = app.views[0]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); +} + +/// 6-Up keeps its three columns and two rows with five documents: closing the sixth leaves the +/// others in their panes with the zoom they had. Side by side, closing one widens every pane, and +/// each document fits its new pane. +#[test] +fn closing_a_document_keeps_the_zoom_of_the_documents_whose_panes_stay() { + let mut app = app_with(6); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 2, 3, 4, 5]); + app.views[1].zoom *= 2.0; + let zoomed = app.views[1].zoom; + app.run("file.close", json!({"index": 5})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.views[1].zoom, zoomed, "the document that kept its pane keeps its zoom"); + + let mut app = app_with(3); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.views[1].zoom *= 2.0; + app.run("file.close", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1]); + let area = view_rects(&app, rects[1], ctx.pixels_per_point()).1; + let v = app.views[1]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its wider pane: {v:?}"); +} + +#[test] +fn tile_refuses_a_layout_it_does_not_have() { + let mut app = app_with(3); + for bad in [json!("5up"), json!("Vertical"), json!(3), json!(null), json!({})] { + let err = app.run("window.arrange.tile", json!({"layout": bad})).unwrap_err(); + assert_eq!(err, "`layout` must be one of grid, vertical, horizontal, 2up, 3up, 4up, 6up", "{bad}"); + assert!(!app.ui.tiled && app.ui.tile_layout == Layout::Grid, "{bad}: the view stays as it is"); + } + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert!(app.run("window.arrange.tile", json!({"layout": "diagonal"})).is_err()); + assert_eq!(app.ui.tile_layout, Layout::Vertical, "a refused layout leaves the tiled one"); + // With one document the layout is still checked, and nothing changes. + let mut one = app_with(1); + assert!(one.run("window.arrange.tile", json!({"layout": "7up"})).is_err()); + assert_eq!(one.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); +} + +#[test] +fn the_tile_items_check_the_layout_the_panes_show() { + let mut app = app_with(3); + let checked = |app: &VectorcraftApp, layout: Option<&str>| { + let p = layout.map_or(serde_json::Value::Null, |l| json!({"layout": l})); + crate::menus::checked(app, "window.arrange.tile", &p) + }; + assert_eq!(checked(&app, None), Some(false), "not tiled"); + app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap(); + assert_eq!(checked(&app, Some("4up")), Some(true)); + assert_eq!(checked(&app, None), Some(false)); + assert_eq!(checked(&app, Some("2up")), Some(false)); + app.run("window.arrange.tile", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(true), "Tile is the grid"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(false)); + // Window › Arrange lists every layout, after Cascade and before Float in Window. + let window = crate::menus::menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, items)| items).unwrap(); + let arrange = window + .into_iter() + .find_map(|i| match i { + crate::menus::Item::Sub("Arrange", items) => Some(items), + _ => None, + }) + .unwrap(); + let labels: Vec<&str> = arrange + .iter() + .filter_map(|i| match i { + crate::menus::Item::Cmd(l, ..) => Some(*l), + _ => None, + }) + .collect(); + assert_eq!( + labels, + [ + "Cascade", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + "Float in Window", + "Float All in Windows", + "Consolidate All Windows" + ] + ); + // Each item's params run, as the menu sends them. + for item in &arrange { + if let crate::menus::Item::Cmd(_, "window.arrange.tile", p) = item { + let p = if p.is_null() { json!({}) } else { p.clone() }; + assert!(app.run("window.arrange.tile", p.clone()).is_ok(), "{p}"); + } + } +} + +/// One frame of the application bar with screen-reader nodes on → the nodes. +fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + app_bar_frame_in(app, ctx, events, 1400.0) +} + +/// [`app_bar_frame`] on a window `width` points wide. +fn app_bar_frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, width: f32) -> Vec { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(width, 800.0)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() +} + +/// The center of the application bar's node whose label, without its leading spaces, is `name` +/// (or starts with it and a shortcut in parentheses). +fn app_bar_node(nodes: &[egui::accesskit::Node], name: &str) -> Option { + let named = |l: &str| l.trim_start().strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with('(')); + let b = nodes.iter().find(|n| n.label().is_some_and(named))?.bounds()?; + Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)) +} + +/// Click the application bar's node labeled `name`. +fn click_app_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let at = app_bar_node(&app_bar_frame(app, ctx, vec![]), name).unwrap_or_else(|| panic!("{name} is drawn")); + app_bar_frame(app, ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + app_bar_frame(app, ctx, vec![button(at, false)]); +} + +#[test] +fn the_arrange_documents_button_tiles_and_consolidates() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + app_bar_frame(&mut app, &ctx, vec![]); + let nodes = app_bar_frame(&mut app, &ctx, vec![]); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands")); + let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search shows")); + assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search: {arrange:?}, {search:?}"); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + let menu = app_bar_frame(&mut app, &ctx, vec![]); + for item in [ + "Consolidate All Windows", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + ] { + assert!(app_bar_node(&menu, item).is_some(), "the menu lists {item}"); + } + click_app_bar(&mut app, &ctx, "Tile All Vertically"); + assert!(app.ui.tiled && app.ui.tile_layout == Layout::Vertical, "{}", app.ui.status); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + click_app_bar(&mut app, &ctx, "Consolidate All Windows"); + assert!(!app.ui.tiled); +} + +/// As the application bar narrows, Arrange Documents goes before the search. +#[test] +fn a_narrow_application_bar_keeps_search_before_arrange_documents() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut search_alone = false; + for width in (200..=1400).rev().step_by(4) { + app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands").is_some()); + assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search"); + search_alone |= search && !arrange; + } + assert!(search_alone, "some width shows the search without Arrange Documents"); +} + #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); @@ -91,7 +426,7 @@ fn tile_shows_a_pane_for_each_document_fitted_to_it() { frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty(), "documents open under their tabs"); let tabbed = app.canvas_rect.unwrap(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); assert_eq!(docs, [0, 1, 2]); @@ -454,7 +789,7 @@ fn arrange_items_follow_the_open_documents() { fn tile_with_one_document_leaves_the_next_one_under_its_tab() { let mut app = app_with(1); let ctx = egui::Context::default(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); assert!(!app.ui.tiled); assert!(!enabled(&app, "window.arrange.consolidateAllWindows")); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); @@ -540,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); @@ -874,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 34d0777c51..8cc87bff47 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()); @@ -1647,6 +1731,37 @@ fn switch_selection_and_drawing_modes_command() { } } +/// Select Last Selection Tool: the Selection tool before any selection tool is chosen, then the +/// one of Selection, Direct Selection and Group Selection chosen last; Magic Wand and Lasso don't +/// count. Running it again keeps that tool, and it changes no art, selection or undo history. +#[test] +fn select_last_selection_tool_command() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let last = |app: &mut VectorcraftApp| app.run("tool.selectLastSelection", json!({})).unwrap(); + let state = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + (st.doc.clone(), st.selection.clone(), st.history.undo.len()) + }; + app.select_tool("pen"); + let before = state(&app); + assert_eq!((last(&mut app), app.session.tool_id()), (json!({"tool": "selection"}), "selection"), "none chosen yet: Selection"); + for id in ["directSelection", "groupSelection", "selection"] { + app.select_tool(id); + app.select_tool("pen"); + assert_eq!(last(&mut app), json!({"tool": id}), "{id}"); + } + app.select_tool("directSelection"); + for other in ["magicWand", "lasso", "rectangle", "hand"] { + app.select_tool(other); + } + assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "Magic Wand and Lasso are not remembered"); + assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "again: the same tool, no cycling"); + assert!(state(&app) == before, "no art, selection or undo step changes"); +} + /// A Switch Selection and Drawing Modes whose tool choice fails returns the error, in both /// directions: the tool stays, the drawing tool to return to stays, and no undo step is added. #[test] @@ -6622,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] @@ -6869,10 +7026,136 @@ fn hidden_char_marks(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec c.fill == blue || c.stroke.color == blue, + Shape::Text(t) => t.fallback_color == blue, + Shape::LineSegment { stroke, .. } => stroke.color == blue, + Shape::Path(p) => p.stroke.color == egui::epaint::ColorMode::Solid(blue), + _ => false, + }) .collect() } +/// Show Hidden Characters marks each tab, nonbreaking space, narrow nonbreaking space, space of +/// a set width and discretionary hyphen with a mark of its kind, a plain space with a dot, and +/// a tab's arrow spans the tab's advance to its stop. +#[test] +fn hidden_characters_mark_tabs_nonbreaking_spaces_and_discretionary_hyphens() { + use super::tool_overlays::CharMark::*; + let text = "a b\tc\u{00A0}d\u{202F}e\u{2003}f\u{2009}g\u{200A}h\u{00AD}i"; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), text, vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + let kinds: Vec<_> = marks.chars.iter().map(|c| c.0).collect(); + assert_eq!(kinds, [Tab, NoBreakSpace, NarrowNoBreakSpace, FixedSpace, FixedSpace, FixedSpace, DiscretionaryHyphen]); + assert_eq!(marks.spaces.len(), 1, "only the plain space has a dot"); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let tab = lay.glyphs.iter().find(|g| text[g.byte..].starts_with('\t')).unwrap(); + assert!(tab.advance > 1.0, "{}", tab.advance); + let (_, a, b) = marks.chars[0]; + let start = t.xf * vectorcraft_geom::Point::new(tab.origin.x, tab.origin.y - 3.0); + assert!((a - start).hypot() < 1e-9 && (b.x - a.x - tab.advance).abs() < 1e-9 && b.y == a.y, "{a:?} {b:?} {start:?}"); +} + +/// Show Hidden Characters marks a line that a forced line break (U+2028) ends with a bent arrow +/// and no ¶; the line a paragraph return ends gets ¶, and the story's end #. +#[test] +fn hidden_characters_mark_forced_line_breaks() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "ab\u{2028}cd\nef", vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert_eq!(lay.lines.len(), 3); + assert_eq!(marks.breaks.len(), 1); + let (at, along, up) = marks.breaks[0]; + let first = &lay.lines[0]; + assert_eq!(at, vectorcraft_geom::Point::new(first.x1 + 1.0, first.baseline)); + assert_eq!((along - at, up - at), (vectorcraft_geom::Vec2::new(1.0, 0.0), vectorcraft_geom::Vec2::new(0.0, -1.0))); + let ends: Vec<_> = marks.ends.iter().map(|e| (e.1, e.0.y)).collect(); + assert_eq!(ends, [("¶", lay.lines[1].baseline), ("#", lay.lines[2].baseline)]); + // A story that ends with a forced line break: the arrow, and # on the empty line after it. + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "ab\u{2028}", vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + assert_eq!((marks.breaks.len(), marks.ends.iter().map(|e| e.1).collect::>()), (1, vec!["#"])); +} + +/// A discretionary hyphen gets one ¬ also where the line breaks at it and the layout draws a +/// hyphen there, which stands for no character of the text. +#[test] +fn hidden_characters_mark_a_discretionary_hyphen_at_a_break_once() { + let style = vectorcraft_doc::CharStyle::default(); + let db = vectorcraft_text::FontDb::global(); + let word = vectorcraft_text::layout(db, &vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "coco-", style.clone())); + let width = word.lines[0].x1 - word.lines[0].x0 + 2.0; + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "coco\u{00AD}co", style); + t.kind = vectorcraft_doc::text::TextKind::Area { + frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Rect::new(0.0, 0.0, width, 400.0).to_path(0.1)), + }; + let lay = vectorcraft_text::layout(db, &t); + assert_eq!(lay.lines.len(), 2, "the line breaks at the discretionary hyphen"); + assert!(lay.glyphs.iter().any(|g| g.len == 0), "the layout draws a hyphen at the break"); + let marks = HiddenMarks::of(&t); + assert_eq!(marks.chars.iter().map(|c| c.0).collect::>(), [super::tool_overlays::CharMark::DiscretionaryHyphen]); +} + +/// In vertical type the marks follow the column: a space's dot sits beside the column, halfway +/// down the space, and ¶ goes below the column's last character. +#[test] +fn hidden_characters_follow_vertical_type() { + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "a b\nc", vectorcraft_doc::CharStyle::default()); + t.vertical = true; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let space = lay.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let marks = HiddenMarks::of(&t); + let dot = marks.spaces[0]; + assert!((dot - vectorcraft_geom::Point::new(space.origin.x + 3.0, space.origin.y + space.advance / 2.0)).hypot() < 1e-9, "{dot:?} {space:?}"); + let (at, glyph, align) = marks.ends[0]; + assert_eq!((glyph, align), ("¶", egui::Align2::CENTER_TOP)); + let b = lay.glyphs.iter().find(|g| g.byte == 2).unwrap(); + assert!(at.y > b.origin.y, "{at:?} below {:?}", b.origin); +} + +/// In a right-to-left paragraph ¶ goes at the line's left end, where the paragraph ends. +#[test] +fn hidden_characters_end_a_right_to_left_line_at_its_left() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "אב גד\nהו", vectorcraft_doc::CharStyle::default()); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.lines[0].rtl); + let marks = HiddenMarks::of(&t); + let (at, glyph, align) = marks.ends[0]; + assert_eq!((glyph, align), ("¶", egui::Align2::RIGHT_BOTTOM)); + assert_eq!(at.x, lay.lines[0].x0 - 1.0); +} + +/// Type on a path has the marks over its characters and # after its last one. +#[test] +fn hidden_characters_mark_type_on_a_path() { + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "a b\tc", vectorcraft_doc::CharStyle::default()); + let path = vectorcraft_geom::Line::new((0.0, 100.0), (600.0, 100.0)).to_path(0.1); + t.kind = vectorcraft_doc::text::TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None }; + let marks = HiddenMarks::of(&t); + assert_eq!(marks.spaces.len(), 1); + assert_eq!(marks.chars.iter().map(|c| c.0).collect::>(), [super::tool_overlays::CharMark::Tab]); + assert_eq!(marks.ends.iter().map(|e| e.1).collect::>(), ["#"]); +} + +/// The overlay draws each kind of mark: a dot, two rings, the tab's arrow, a tick, ¬, the forced +/// line break's bent arrow, ¶ and #. +#[test] +fn show_hidden_characters_draws_every_kind_of_mark() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let text = "a b\tc\u{00A0}d\u{202F}e\u{2003}f\u{00AD}g\u{2028}h\ni"; + app.session.execute("text.create", &json!({"x": 20, "y": 60, "text": text})).unwrap(); + let ctx = egui::Context::default(); + let xf = Xf { rect: egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 1.0, center: Point::new(200.0, 150.0), rot: 0.0 }; + let shapes = hidden_chars(&mut app, &ctx, &xf); + let count = |f: &dyn Fn(&Shape) -> bool| shapes.iter().filter(|s| f(s)).count(); + assert_eq!(count(&|s| matches!(s, Shape::Circle(c) if c.fill != Color32::TRANSPARENT)), 1, "{shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Circle(c) if c.fill == Color32::TRANSPARENT)), 2, "{shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::LineSegment { .. })), 2, "the tab's shaft and the tick: {shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Path(_))), 3, "the tab's head and the break's arrow: {shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Text(_))), 3, "¬, ¶ and #: {shapes:?}"); +} + /// Show Hidden Characters puts a dot over each space of a list paragraph and none over its /// bullet, which stands for no character. #[test] @@ -6890,7 +7173,7 @@ fn hidden_characters_mark_no_space_at_a_bullet() { fn show_hidden_characters_off_releases_the_text_nodes() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let text = json!({"x": 20, "y": 60, "text": "one two\nthree four"}); + let text = json!({"x": 20, "y": 60, "text": "one\ttwo\u{00A0}x\nthree\u{2028}four"}); let id = vectorcraft_doc::NodeId(app.session.execute("text.create", &text).unwrap()["id"].as_u64().unwrap()); let ctx = egui::Context::default(); app.run("type.hiddenCharacters", json!({})).unwrap(); @@ -8732,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)]); @@ -8819,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()); @@ -8871,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()); @@ -8883,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(); @@ -8894,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()); @@ -10507,8 +10985,8 @@ fn frame_moves_stop_at_the_button_up() { let up = egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c), egui::Event::PointerMoved(d)]; let feed = StylusFeed::default(); - let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; - let after = PenPose { tilt: Some([50.0, 0.0]), rotation: None }; + let at_b = PenPose { tilt: Some([20.0, 0.0]), ..PenPose::default() }; + let after = PenPose { tilt: Some([50.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, after), (0.8, after)] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -10533,7 +11011,7 @@ fn frame_moves_keep_the_last_move_when_the_button_went_up_elsewhere() { let up = egui::Event::PointerButton { pos: up_at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c)]; let feed = StylusFeed::default(); - let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; + let at_b = PenPose { tilt: Some([20.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, PenPose::default())] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -10559,7 +11037,7 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { assert_eq!(mouse, [(a, None, None), (b, None, None)], "the last move follows the normal pointer path"); // A macOS pen: the feed kept a pressure and a pose for each move, the last for the last. let feed = StylusFeed::default(); - let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: None }; + let leaning = PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.9, leaning), (0.3, leaning), (0.0, PenPose::default()), (0.5, leaning)] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -11004,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] @@ -11038,7 +11556,7 @@ fn the_hosts_pen_tilt_and_rotation_reach_the_paintbrush() { assert_eq!(cmd, "path.freehand"); p["points"].as_array().unwrap().iter().map(|s| [3, 4, 5].map(|i| s.get(i).and_then(serde_json::Value::as_f64))).collect() }; - let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: Some(45.0) }; + let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: Some(45.0), wheel: None }; let points = stroke(&mut app, 260.0, Some(leaning)); assert!(!points.is_empty() && points.iter().all(|p| *p == [Some(30.0), Some(0.0), Some(45.0)]), "{points:?}"); // With the view rotated 90° clockwise, a pen leaning to the right of the screen leans up the @@ -11069,7 +11587,7 @@ fn moves_in_the_release_frame_reach_the_paintbrush_with_their_tilt() { let moved = |tilt: f32| { feed.set_move(crate::stylus::PenSample { pressure: 0.5, - pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0) }, + pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0), wheel: None }, ..Default::default() }) }; @@ -11112,8 +11630,11 @@ fn the_last_move_of_a_frame_keeps_its_own_tilt() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); let at = |x: f64| xf.to_screen(Point::new(x, 300.0)); let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - let sample = - |tilt: f32| crate::stylus::PenSample { pressure: 0.5, pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0) }, ..Default::default() }; + let sample = |tilt: f32| crate::stylus::PenSample { + pressure: 0.5, + pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0), wheel: None }, + ..Default::default() + }; feed.set_move(sample(10.0)); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(300.0)), button(at(300.0), true)]); feed.set_move(sample(20.0)); @@ -12605,6 +13126,168 @@ fn text_threads_run_from_each_out_port_to_the_next_in_port() { assert!(thread_overlays(&app, zoom).is_empty()); } +#[test] +fn text_thread_overlays_keep_document_order_with_mixed_selection() { + use vectorcraft_doc::NodeId; + use vectorcraft_tools::text::{Port, port_centre}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let text = "Words that fill more than the frame holds. ".repeat(10); + let id = |value: serde_json::Value| NodeId(value["id"].as_u64().unwrap()); + let first = id(app.run("text.create", json!({"x": 20, "y": 20, "text": text, "area": {"width": 150, "height": 60}})).unwrap()); + let first_next = id(app.run("text.thread.add", json!({"from": first.0, "at": [300, 20]})).unwrap()); + let second = id(app + .run( + "text.create", + json!({"x": 20, "y": 200, "text": "Words that fill more than the frame holds. ".repeat(10), "area": {"width": 150, "height": 60}}), + ) + .unwrap()); + let second_next = id(app.run("text.thread.add", json!({"from": second.0, "at": [300, 200]})).unwrap()); + let unselected = id(app + .run("text.create", json!({"x": 20, "y": 100, "text": "An unselected story. ".repeat(20), "area": {"width": 150, "height": 60}})) + .unwrap()); + let unselected_next = id(app.run("text.thread.add", json!({"from": unselected.0, "at": [300, 100]})).unwrap()); + let unrelated_a = id(app.run("shape.rectangle", json!({"x": 450, "y": 300, "width": 20, "height": 20})).unwrap()); + let unrelated_b = id(app.run("shape.rectangle", json!({"x": 480, "y": 300, "width": 20, "height": 20})).unwrap()); + app.run("select.set", json!({"ids": [unrelated_a.0, unrelated_b.0, second_next.0, first.0]})).unwrap(); + + let state = app.session.active().unwrap(); + assert_eq!(state.selection.objects, [unrelated_a, unrelated_b, second_next, first]); + assert_eq!(state.doc.text_threads, [vec![first, first_next], vec![second, second_next], vec![unselected, unselected_next]]); + let frame = |id| match &state.doc.node(id).unwrap().kind { + NodeKind::Text(text) => (**text).clone(), + _ => panic!("thread member is text"), + }; + let px = 1.0; + let expected = [ + (port_centre(&frame(first), Port::Out, px).unwrap(), port_centre(&frame(first_next), Port::In, px).unwrap()), + (port_centre(&frame(second), Port::Out, px).unwrap(), port_centre(&frame(second_next), Port::In, px).unwrap()), + ]; + let overlays = thread_overlays(&app, 1.0); + let lines: Vec<_> = overlays + .iter() + .filter_map(|overlay| match overlay { + Overlay::Line { a, b, .. } if expected.iter().any(|(from, to)| *a == *from && *b == *to) => Some((*a, *b)), + _ => None, + }) + .collect(); + assert_eq!(lines, expected, "thread lines follow document order, not selection order"); + assert_eq!(overlays.iter().filter(|overlay| matches!(overlay, Overlay::Line { .. })).count(), 14, "two thread links and their port arrows only"); + let ports: Vec<_> = overlays + .iter() + .filter_map(|overlay| match overlay { + Overlay::Highlight { quad, .. } => Some(quad[0].midpoint(quad[2])), + _ => None, + }) + .collect(); + assert_eq!(ports, expected.into_iter().flat_map(|(from, to)| [from, to]).collect::>()); +} + +/// Two document-order threads hit the first two selected IDs among 512 unrelated paths. +/// Their real port geometry and document-order output remain unchanged. +#[test] +fn text_thread_overlays_keep_two_early_hits_with_many_unrelated_paths() { + use std::sync::Arc; + use vectorcraft_doc::NodeId; + use vectorcraft_tools::text::{Port, port_centre, ports_shown}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let text = "Words that fill more than the frame holds. ".repeat(10); + let id = |value: serde_json::Value| NodeId(value["id"].as_u64().unwrap()); + let mut threads = vec![]; + for y in [20, 200] { + let first = id(app.run("text.create", json!({"x": 20, "y": y, "text": text, "area": {"width": 150, "height": 60}})).unwrap()); + let next = id(app.run("text.thread.add", json!({"from": first.0, "at": [300, y]})).unwrap()); + threads.push([first, next]); + } + let path = id(app.run("shape.rectangle", json!({"x": 450, "y": 300, "width": 20, "height": 20})).unwrap()); + let mut selected = vec![threads[0][0], threads[1][0], path]; + { + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let template = doc.node(path).unwrap().clone(); + let mut additions = Vec::with_capacity(511); + for _ in 1..512 { + let mut p = template.clone(); + p.id = doc.alloc_id(); + selected.push(p.id); + additions.push(Arc::new(p)); + } + Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().extend(additions); + doc.drop_lookup_cache(); + } + app.run("select.set", json!({"ids": selected.iter().map(|id| id.0).collect::>()})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.text_threads, threads.iter().map(|t| t.to_vec()).collect::>()); + assert_eq!(st.selection.objects, selected); + assert_eq!(st.selection.objects.len(), 514); + assert!(ports_shown(&st.doc, &st.selection.objects)); + let frame = |id| match &st.doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("thread member is text"), + }; + let expected: Vec<_> = + threads.iter().map(|[a, b]| (port_centre(&frame(*a), Port::Out, 1.0).unwrap(), port_centre(&frame(*b), Port::In, 1.0).unwrap())).collect(); + let overlays = thread_overlays(&app, 1.0); + let links: Vec<_> = overlays + .iter() + .filter_map(|o| match o { + Overlay::Line { a, b, .. } if expected.contains(&(*a, *b)) => Some((*a, *b)), + _ => None, + }) + .collect(); + assert_eq!(links, expected, "the two thread links stay in document order"); + assert_eq!(overlays.iter().filter(|o| matches!(o, Overlay::Line { .. })).count(), 14, "two links and their port arrows only"); + let ports: Vec<_> = overlays + .iter() + .filter_map(|o| match o { + Overlay::Highlight { quad, .. } => Some(quad[0].midpoint(quad[2])), + _ => None, + }) + .collect(); + assert_eq!(ports, expected.into_iter().flat_map(|(a, b)| [a, b]).collect::>()); +} + +/// One two-frame thread misses a selection of 512 unrelated paths. +/// This checks ordinary empty output, not elapsed time or allocation. +#[test] +fn text_thread_overlays_skip_one_unselected_thread_with_many_unrelated_paths() { + use std::sync::Arc; + use vectorcraft_doc::NodeId; + use vectorcraft_tools::text::{ported, ports_shown}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let text = "Words that fill more than the frame holds. ".repeat(10); + let id = |value: serde_json::Value| NodeId(value["id"].as_u64().unwrap()); + let first = id(app.run("text.create", json!({"x": 20, "y": 20, "text": text, "area": {"width": 150, "height": 60}})).unwrap()); + let next = id(app.run("text.thread.add", json!({"from": first.0, "at": [300, 20]})).unwrap()); + let path = id(app.run("shape.rectangle", json!({"x": 450, "y": 300, "width": 20, "height": 20})).unwrap()); + let mut selected = vec![path]; + { + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let template = doc.node(path).unwrap().clone(); + let mut additions = Vec::with_capacity(511); + for _ in 1..512 { + let mut p = template.clone(); + p.id = doc.alloc_id(); + selected.push(p.id); + additions.push(Arc::new(p)); + } + Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().extend(additions); + doc.drop_lookup_cache(); + } + app.run("select.set", json!({"ids": selected.iter().map(|id| id.0).collect::>()})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.text_threads, [vec![first, next]]); + assert_eq!(st.selection.objects, selected); + assert_eq!(st.selection.objects.len(), 512); + assert!(selected.iter().all(|id| *id != first && *id != next)); + assert!([first, next].into_iter().all(|id| ported(&st.doc, id).is_some()), "both thread frames have ports"); + assert!(ports_shown(&st.doc, &st.selection.objects)); + assert!(thread_overlays(&app, 1.0).is_empty()); +} + /// A double-click with the Selection tool on the out port of a threaded frame breaks the /// thread there: no new frame is threaded on, and the story flows back into the first frame. #[test] @@ -12655,6 +13338,103 @@ fn text_threads_of_a_huge_selection_have_lines_but_no_ports() { assert!(!o.iter().any(|x| matches!(x, Overlay::Highlight { .. } | Overlay::Path { .. })), "no port boxes"); } +/// An ignored diagnostic for the miss-heavy selection-membership work in `thread_overlays`. +/// Construct the document and selection before timing: T unrelated threads of F frames each miss +/// in a selection of S ordinary paths. There is deliberately no timing threshold; run on an idle +/// machine and compare the printed cases. +#[test] +#[ignore = "manual performance diagnostic; no stable timing threshold"] +fn thread_overlays_miss_heavy_selection_membership_diagnostic() { + use std::sync::Arc; + use std::time::Instant; + use vectorcraft_doc::NodeId; + use vectorcraft_tools::text::ported; + + fn fixture(threads: usize, frames_per_thread: usize, selected: usize) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let text = "Words that fill more than the frame holds. ".repeat(10); + let first = NodeId( + app.run("text.create", json!({"x": 20, "y": 20, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(), + ); + let second = NodeId(app.run("text.thread.add", json!({"from": first.0, "at": [300, 200]})).unwrap()["id"].as_u64().unwrap()); + let path = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let (thread_ids, selected_ids) = { + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let first_template = doc.node(first).unwrap().clone(); + let second_template = doc.node(second).unwrap().clone(); + let path_template = doc.node(path).unwrap().clone(); + let mut thread_ids = vec![vec![first, second]]; + let mut additions = Vec::with_capacity( + (threads.saturating_sub(1) * frames_per_thread) + frames_per_thread.saturating_sub(2) + selected.saturating_sub(1), + ); + + for _ in 2..frames_per_thread { + let mut next = second_template.clone(); + next.id = doc.alloc_id(); + thread_ids[0].push(next.id); + additions.push(Arc::new(next)); + } + + for _ in 1..threads { + let mut a = first_template.clone(); + a.id = doc.alloc_id(); + let mut b = second_template.clone(); + b.id = doc.alloc_id(); + let mut thread = vec![a.id, b.id]; + additions.push(Arc::new(a)); + additions.push(Arc::new(b)); + for _ in 2..frames_per_thread { + let mut next = second_template.clone(); + next.id = doc.alloc_id(); + thread.push(next.id); + additions.push(Arc::new(next)); + } + thread_ids.push(thread); + } + + let mut selected_ids = vec![path]; + for _ in 1..selected { + let mut p = path_template.clone(); + p.id = doc.alloc_id(); + selected_ids.push(p.id); + additions.push(Arc::new(p)); + } + + doc.text_threads = thread_ids.clone(); + Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().extend(additions); + doc.drop_lookup_cache(); + (thread_ids, selected_ids) + }; + app.run("select.set", json!({"ids": selected_ids.iter().map(|id| id.0).collect::>()})).unwrap(); + + let st = app.session.active().unwrap(); + assert_eq!(st.doc.text_threads, thread_ids); + assert!(thread_ids.iter().all(|thread| thread.len() == frames_per_thread)); + assert_eq!(st.selection.objects, selected_ids); + assert!(thread_ids.iter().flatten().all(|id| ported(&st.doc, *id).is_some()), "all thread frames have ports"); + assert!(selected_ids.iter().all(|id| thread_ids.iter().flatten().all(|frame| frame != id)), "selection misses every thread"); + app + } + + const REPEATS: usize = 2_000; + for (threads, frames_per_thread, selected) in [(256, 2, 256), (256, 2, 512), (512, 2, 256), (512, 2, 512), (512, 2, 1), (1, 1024, 512)] { + let app = fixture(threads, frames_per_thread, selected); + let st = app.session.active().unwrap(); + assert!(vectorcraft_tools::text::ports_shown(&st.doc, &st.selection.objects)); + + // Warm Document's id index and verify the negative output before timing. + assert!(thread_overlays(&app, 1.0).is_empty()); + let started = Instant::now(); + for _ in 0..REPEATS { + let overlays = thread_overlays(std::hint::black_box(&app), 1.0); + assert!(overlays.is_empty()); + } + println!("thread_overlays diagnostic T={threads} F={frames_per_thread} S={selected} repeats={REPEATS} elapsed={:?}", started.elapsed()); + } +} + /// A frame of a thread in perspective has no ports: Show Text Threads draws no port box on it /// and no line to or from it; the links between frames with ports keep theirs. #[test] diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index bc94f19e2b..bff6f174b9 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -2,12 +2,14 @@ use super::grid::{clip_segment, pref_color}; use super::outline::{OVERLAY_MAX_ANCHORS, c32, stroke_path}; use super::{Color32, CornerRadius, Node, NodeKind, Overlay, Point, Pos2, Rect, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, pos2, vec2}; -/// Type → Show Hidden Characters: spaces as dots, ¶ at paragraph ends, # at the end of a story. -/// The marks of each text object are kept from one frame to the next ([`HiddenChars`]). +/// Type → Show Hidden Characters: the characters that print no ink, and the ends of paragraphs, +/// lines and stories ([`HiddenMarks`]). The marks of each text object are kept from one frame to +/// the next ([`HiddenChars`]). pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { let Some(st) = app.session.active() else { return }; let clip = p.clip_rect(); let color = Color32::from_rgb(0x4f, 0x9d, 0xff); + let stroke = Stroke::new(1.0, color); let font = egui::FontId::proportional(((10.0 * xf.zoom) as f32).clamp(7.0, 18.0)); let kept = &mut app.canvas.hidden_chars; // `last` holds the marks of the last frame. The marks of the objects this frame doesn't draw @@ -43,13 +45,62 @@ pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, for &at in &marks.spaces { p.circle_filled(xf.to_screen(at), 1.2, color); } - for &(at, glyph) in &marks.ends { - p.text(xf.to_screen(at), egui::Align2::LEFT_BOTTOM, glyph, font.clone(), color); + for &(mark, a, b) in &marks.chars { + draw_char_mark(p, mark, xf.to_screen(a), xf.to_screen(b), stroke, &font); + } + for &(at, along, up) in &marks.breaks { + let at = xf.to_screen(at); + let u = unit_or(xf.to_screen(along) - at, vec2(1.0, 0.0)); + let n = unit_or(xf.to_screen(up) - at, vec2(0.0, -1.0)); + // A bent arrow: down from above the line's end, then back along the line. + let corner = at + u * 7.0 + n * 2.0; + let tip = at + u + n * 2.0; + p.add(Shape::line(vec![at + u * 7.0 + n * 8.0, corner, tip], stroke)); + p.add(Shape::line(vec![tip + u * 3.0 + n * 3.0, tip, tip + u * 3.0 - n * 3.0], stroke)); + } + for &(at, glyph, align) in &marks.ends { + p.text(xf.to_screen(at), align, glyph, font.clone(), color); } kept.marks.insert(n.id, (n.clone(), marks)); }); } +/// `v` scaled to length 1, or `or` when `v` has no length. +fn unit_or(v: egui::Vec2, or: egui::Vec2) -> egui::Vec2 { + let len = v.length(); + if len > 1e-3 { v / len } else { or } +} + +/// Draws the mark of one character on screen. `a` and `b` are the start and end of the +/// character's advance, in the direction the text reads, above its baseline. +fn draw_char_mark(p: &egui::Painter, mark: CharMark, a: Pos2, b: Pos2, stroke: Stroke, font: &egui::FontId) { + let u = unit_or(b - a, vec2(1.0, 0.0)); + let mid = a + (b - a) * 0.5; + match mark { + CharMark::Tab => { + // An arrow across the tab's advance, at least 6 px long. + let end = if (b - a).length() < 6.0 { a + u * 6.0 } else { b }; + let n = vec2(u.y, -u.x); + p.line_segment([a, end], stroke); + p.add(Shape::line(vec![end - u * 3.0 + n * 2.5, end, end - u * 3.0 - n * 2.5], stroke)); + } + CharMark::NoBreakSpace => { + p.circle_stroke(mid, 2.0, stroke); + } + CharMark::NarrowNoBreakSpace => { + p.circle_stroke(mid, 1.4, stroke); + } + CharMark::FixedSpace => { + // A short tick across the baseline's direction. + let n = vec2(u.y, -u.x) * 2.5; + p.line_segment([mid - n, mid + n], stroke); + } + CharMark::DiscretionaryHyphen => { + p.text(mid, egui::Align2::CENTER_BOTTOM, "¬", font.clone(), stroke.color); + } + } +} + /// The Show Hidden Characters marks of the text objects drawn in the last frame /// ([`crate::CanvasCache::hidden_chars`]). Each is kept with the object it was laid out from: an /// edited object is a new `Arc` and is laid out again, and all type is laid out again when the @@ -63,12 +114,51 @@ pub struct HiddenChars { pub(super) marks: std::collections::HashMap, std::sync::Arc)>, } -/// One text object's marks in document space: a dot over each space, and ¶ or # after the lines -/// that end a paragraph or the story. Type on a path has none. +/// The mark Show Hidden Characters draws over a character other than a plain space. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum CharMark { + /// A tab (U+0009): an arrow across its advance, to the tab stop. + Tab, + /// A nonbreaking space (U+00A0): a ring. + NoBreakSpace, + /// A narrow nonbreaking space (U+202F): a smaller ring. + NarrowNoBreakSpace, + /// The spaces of a set width (U+2000 to U+200A, U+205F, U+3000): a short tick. + FixedSpace, + /// A discretionary hyphen (U+00AD): ¬, where the word can break. + DiscretionaryHyphen, +} + +impl CharMark { + /// The mark of `c`, `None` for a character with no mark of its own. + pub(super) fn of(c: char) -> Option { + Some(match c { + '\t' => Self::Tab, + '\u{00A0}' => Self::NoBreakSpace, + '\u{202F}' => Self::NarrowNoBreakSpace, + '\u{2000}'..='\u{200A}' | '\u{205F}' | '\u{3000}' => Self::FixedSpace, + '\u{00AD}' => Self::DiscretionaryHyphen, + _ => return None, + }) + } +} + +/// One text object's marks in document space: a dot over each space, a [`CharMark`] over each +/// tab, nonbreaking space, space of a set width and discretionary hyphen, a bent arrow after +/// each line a forced line break (U+2028) ends, and ¶ or # after the lines that end a paragraph +/// or the story. Type on a path has the marks over characters, ¶ and the bent arrow at its +/// breaks, and # after its last character when all of its text is drawn. #[derive(Default)] pub(super) struct HiddenMarks { pub(super) spaces: Vec, - ends: Vec<(Point, &'static str)>, + /// Each mark over a character, with the start and end of the character's advance 3 pt above + /// its baseline, in the direction the text reads. + pub(super) chars: Vec<(CharMark, Point, Point)>, + /// Each forced line break: where its arrow starts, a point 1 pt further along the line and a + /// point 1 pt above the baseline from there. + pub(super) breaks: Vec<(Point, Point, Point)>, + /// ¶ and #, where they are drawn and how the text is aligned to that point. + pub(super) ends: Vec<(Point, &'static str, egui::Align2)>, } impl HiddenMarks { @@ -76,29 +166,71 @@ impl HiddenMarks { pub(super) fn of(tx: &vectorcraft_doc::TextObject) -> Self { let mut marks = Self::default(); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx); - if lay.on_path { - return marks; - } let text = tx.plain_text(); let to = |q: Point| tx.xf * q; - // A list marker's glyphs (length 0) stand for no character. - for g in lay.glyphs.iter().filter(|g| g.len > 0) { - if text.get(g.byte..).is_some_and(|s| s.starts_with(' ')) { - marks.spaces.push(to(Point::new(g.origin.x + g.advance / 2.0, g.origin.y - 3.0))); + // The direction a glyph's baseline runs, and up from it (y points down). + let along = |angle: f64| vectorcraft_geom::Vec2::new(angle.cos(), angle.sin()); + let up = |angle: f64| { + let d = along(angle); + vectorcraft_geom::Vec2::new(d.y, -d.x) + }; + // A list marker's glyphs and a hyphen the layout adds at a break (length 0) stand for no + // character. Glyphs before the start of an open path draw nothing. A character drawn with + // several glyphs gets one mark. + let mut marked = None; + for g in lay.glyphs.iter().filter(|g| g.len > 0 && !g.off_path) { + let Some(c) = text.get(g.byte..).and_then(|s| s.chars().next()) else { continue }; + if marked == Some(g.byte) { + continue; } + let (d, n) = (along(g.angle), up(g.angle)); + let start = g.origin + n * 3.0; + let end = start + d * g.advance; + if c == ' ' { + marks.spaces.push(to(start + d * (g.advance / 2.0))); + } else if let Some(mark) = CharMark::of(c) { + let (a, b) = if g.rtl { (end, start) } else { (start, end) }; + marks.chars.push((mark, to(a), to(b))); + } else if lay.on_path && (c == '\n' || c == '\u{2028}') { + // Type on a path is one line: its breaks are marked where their glyphs are. + if c == '\n' { + marks.ends.push((to(g.origin), "¶", egui::Align2::LEFT_BOTTOM)); + } else { + marks.breaks.push((to(g.origin), to(g.origin + d), to(g.origin + d + n))); + } + } else { + continue; + } + marked = Some(g.byte); } + if lay.on_path { + // # after the last character, when the path holds all of the text. + let last = lay.glyphs.iter().filter(|g| g.len > 0 && !g.off_path).max_by_key(|g| g.byte + g.len); + if let Some(g) = last.filter(|g| g.byte + g.len >= text.len() && !lay.overflow) { + let d = along(g.angle); + let at = if g.rtl { g.origin - d } else { g.origin + d * (g.advance + 1.0) }; + marks.ends.push((to(at), "#", egui::Align2::LEFT_BOTTOM)); + } + return marks; + } + // Lines are in line space: `physical_point` turns them into columns in vertical type. + let at = |x: f64, y: f64| to(lay.physical_point(Point::new(x, y))); for (i, line) in lay.lines.iter().enumerate() { let last = i + 1 == lay.lines.len(); - let breaks = text.get(line.end..).is_some_and(|s| s.starts_with('\n')); - let (glyph, at) = if last && line.end >= text.len() { - ("#", true) - } else if breaks { - ("¶", true) - } else { - ("", false) + // A right-to-left line ends at its left edge. + let (x, dx) = if line.rtl { (line.x0 - 1.0, -1.0) } else { (line.x1 + 1.0, 1.0) }; + let align = match (lay.vertical, line.rtl) { + (true, _) => egui::Align2::CENTER_TOP, + (false, true) => egui::Align2::RIGHT_BOTTOM, + (false, false) => egui::Align2::LEFT_BOTTOM, }; - if at { - marks.ends.push((to(Point::new(line.x1 + 1.0, line.baseline)), glyph)); + let soft = text.get(line.start..line.end).is_some_and(|s| s.ends_with('\u{2028}')); + if last && line.end >= text.len() { + marks.ends.push((at(x, line.baseline), "#", align)); + } else if soft { + marks.breaks.push((at(x, line.baseline), at(x + dx, line.baseline), at(x, line.baseline - 1.0))); + } else if text.get(line.end..).is_some_and(|s| s.starts_with('\n')) { + marks.ends.push((at(x, line.baseline), "¶", align)); } } marks @@ -314,13 +446,37 @@ pub(super) type Underlines = std::sync::Arc>; /// [`vectorcraft_tools::text::PORTS_MAX`] such frames selected the tools draw no ports, and only /// the lines are drawn here. `zoom`: screen pixels to the document unit. pub(super) fn thread_overlays(app: &VectorcraftApp, zoom: f64) -> Vec { + use std::collections::HashSet; + use vectorcraft_doc::NodeId; use vectorcraft_tools::text::{Port, PortState, port_centre, ported, ports_shown, push_port}; let Some(st) = app.session.active() else { return vec![] }; let px = 1.0 / zoom.max(1e-9); let boxes = ports_shown(&st.doc, &st.selection.objects); + let selection = &st.selection.objects; + let mut selected: Option> = None; + // The first two full searches need no index. + let mut full_searches = 0; + let mut is_selected = |id: &NodeId| { + if selection.len() <= 1 { + return selection.contains(id); + } + if full_searches == 0 { + full_searches = 1; + return selection.contains(id); + } + // Two early selection hits need no index. + if selected.is_none() && selection[..2].contains(id) { + return true; + } + if selected.is_none() && full_searches < 2 { + full_searches += 1; + return selection.contains(id); + } + selected.get_or_insert_with(|| selection.iter().copied().collect::>()).contains(id) + }; let mut o = vec![]; for thread in &st.doc.text_threads { - if !thread.iter().any(|id| st.selection.objects.contains(id)) { + if !thread.iter().any(&mut is_selected) { continue; } let color = st.doc.layer_color(thread[0]); diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 4443f12997..e0e5cc9f75 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -94,7 +94,7 @@ pub(super) const HOLD_DELAY: f32 = 0.3; /// …and how fast it zooms then (as `exp(seconds × HOLD_ZOOM)`: twice as close each second). pub(super) const HOLD_ZOOM: f64 = std::f64::consts::LN_2; -/// Performance › Animated Zoom, which needs GPU Performance as in Illustrator: the Zoom tool zooms +/// Performance › Animated Zoom, which needs GPU Performance: the Zoom tool zooms /// as it is dragged sideways or held, instead of zooming to the area dragged across, and a wheel /// notch's zoom glides in ([`wheel`]). pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index dc9f9fa848..43b9f5b69c 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -36,7 +36,7 @@ use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title} pub use tabs::{doc_tabs, isolation_bar, step_document}; pub(crate) use tabs::{document_window_title, show_document, window_tab}; -/// The application bar's height, in points (compact, as in PhotoCraft). +/// The application bar's height, in points (compact). pub const APP_BAR_HEIGHT: f32 = 32.0; /// The brand mark's side. const MARK: f32 = 18.0; @@ -110,7 +110,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { gap: ui.spacing().item_spacing.x, community: crate::community::discord_width(ui, false), }); - let (switcher, ws_w, learn, discord) = (fit.switcher, fit.switcher_w, fit.learn, fit.community); + let (switcher, ws_w, arrange, learn, discord) = (fit.switcher, fit.switcher_w, fit.arrange, fit.learn, fit.community); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; // Workspace switcher: shows the current workspace, opens Window → Workspace. @@ -129,6 +129,11 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.add_space(8.0); } + // Arrange Documents: Consolidate All Windows and the Tile layouts. + if arrange { + let resp = widgets::icon_button(ui, "layout-grid", tl!("Arrange Documents"), app.ui.tiled, BAR_ICON); + egui::Popup::menu(&resp).show(|ui| arrange_documents_popup(app, ui)); + } // Search → command palette (its shortcut opens it too). let with_shortcut = |text: &str| match &field.shortcut { Some(sc) => format!("{text} ({sc})"), @@ -181,7 +186,34 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// The side of the app bar's square icon buttons (the search icon, Explore tutorials). +/// The Arrange Documents menu ([`menus::arrange_documents_items`]): each item as the Window menu +/// shows it, grayed out while its command can't run, the Tile layout the panes show checked. +fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) { + ui.set_min_width(200.0); + let mut clicked = None; + for it in menus::arrange_documents_items() { + match it { + menus::Item::Sep => { + ui.separator(); + } + menus::Item::Cmd(label, id, p) => { + let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue }; + let label = crate::i18n::t_id(id, label); + let text = if checked == Some(true) { format!("✓ {label}") } else { format!(" {label}") }; + if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() { + clicked = Some((id, if p.is_null() { json!({}) } else { p })); + ui.close(); + } + } + _ => {} + } + } + if let Some((id, p)) = clicked { + menus::invoke(app, id, p); + } +} + +/// The side of the app bar's square icon buttons (the search icon, Arrange Documents, Explore tutorials). const BAR_ICON: f32 = 28.0; /// The narrowest the workspace switcher gets. const MIN_SWITCHER: f32 = 64.0; @@ -225,6 +257,8 @@ struct RightGroup { switcher_w: f32, /// How the search shows. search: Search, + /// Whether Arrange Documents shows. + arrange: bool, /// Whether Explore tutorials shows. learn: bool, /// Whether the community button shows. @@ -232,8 +266,8 @@ struct RightGroup { } /// The right-hand group for the room it has. As the room runs short, the community button goes first -/// (it is also under Help), then Explore tutorials (also Window › Learn), then the search field becomes the -/// search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe +/// (it is also under Help), then Explore tutorials (also Window › Learn), then Arrange Documents (also Window › +/// Arrange), then the search field becomes the search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe /// Mode the label's width is taken first, and the switcher (also under Window › Workspace) goes when /// a minimal one does not fit. fn fit_right_group(w: &RightWidths) -> RightGroup { @@ -254,10 +288,12 @@ fn fit_right_group(w: &RightWidths) -> RightGroup { Search::Hidden => 0.0, }; let switcher_w = w.switcher.min(room - 8.0 - search_w).max(MIN_SWITCHER); - let learn_end = switcher_w + 8.0 + search_w + w.gap + w.icon; - let learn = field && room >= learn_end; + let arrange_end = switcher_w + 8.0 + search_w + w.gap + w.icon; + let arrange = field && room >= arrange_end; + let learn_end = arrange_end + w.gap + w.icon; + let learn = arrange && room >= learn_end; let community = learn && room >= learn_end + 10.0 + w.gap + w.community; - RightGroup { switcher, switcher_w, search, learn, community } + RightGroup { switcher, switcher_w, search, arrange, learn, community } } /// The app bar's search field: a button drawn as a field. The command palette's popup holds the diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 71b737dbfc..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 { @@ -886,7 +975,7 @@ fn gripper(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, d } } -/// The Control bar (Window → Control), context-sensitive like Illustrator's, docked to the top or +/// The Control bar (Window → Control), context-sensitive, docked to the top or /// the bottom of the window, or floating over the window below the menu bar, where it takes no room /// from the canvas. A floating bar is [`FLOAT_WIDTH`] wide, or as wide as the window when that is /// narrower, and is kept inside the window when the window shrinks. @@ -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 61c67e6a70..4c9506b13c 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -172,11 +172,11 @@ fn right_stage(g: &super::RightGroup) -> String { w if w > super::MIN_SWITCHER => "narrower switcher", _ => "minimal switcher", }; - format!("community {}, learn {}, {:?}, {switcher}", g.community, g.learn, g.search) + format!("community {}, learn {}, arrange {}, {:?}, {switcher}", g.community, g.learn, g.arrange, g.search) } -/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then the search -/// field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes. +/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then Arrange +/// Documents, then the search field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes. /// Whatever shows fits in the room, down to the minimal switcher alone. #[test] fn the_app_bar_gives_up_its_right_hand_controls_in_order() { @@ -193,31 +193,33 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() { super::Search::Icon => w.gap + w.icon, super::Search::Hidden => 0.0, }; + let arrange = if g.arrange { w.gap + w.icon } else { 0.0 }; let learn = if g.learn { w.gap + w.icon } else { 0.0 }; let community = if g.community { 10.0 + w.gap + w.community } else { 0.0 }; - let used = g.switcher_w + 8.0 + search + learn + community; + let used = g.switcher_w + 8.0 + search + arrange + learn + community; assert!(used <= room || g.switcher_w == super::MIN_SWITCHER && g.search == super::Search::Hidden, "{room}: {g:?} needs {used}"); } assert_eq!( stages, [ - "community true, learn true, Field, full switcher", - "community false, learn true, Field, full switcher", - "community false, learn false, Field, full switcher", - "community false, learn false, Icon, full switcher", - "community false, learn false, Icon, narrower switcher", - "community false, learn false, Icon, minimal switcher", + "community true, learn true, arrange true, Field, full switcher", + "community false, learn true, arrange true, Field, full switcher", + "community false, learn false, arrange true, Field, full switcher", + "community false, learn false, arrange false, Field, full switcher", + "community false, learn false, arrange false, Icon, full switcher", + "community false, learn false, arrange false, Icon, narrower switcher", + "community false, learn false, arrange false, Icon, minimal switcher", // Once the icon has gone, the switcher takes the room it leaves. - "community false, learn false, Hidden, narrower switcher", - "community false, learn false, Hidden, minimal switcher", + "community false, learn false, arrange false, Hidden, narrower switcher", + "community false, learn false, arrange false, Hidden, minimal switcher", ] ); // In Safe Mode the label's width is taken first (not counted in `room`), and the switcher goes // when a minimal one does not fit. let safe = |room| right_stage(&super::fit_right_group(&right_widths(room, true))); - assert_eq!(safe(700.0), "community true, learn true, Field, full switcher"); - assert_eq!(safe(72.0), "community false, learn false, Hidden, minimal switcher"); - assert_eq!(safe(71.0), "community false, learn false, Hidden, no switcher"); + assert_eq!(safe(700.0), "community true, learn true, arrange true, Field, full switcher"); + assert_eq!(safe(72.0), "community false, learn false, arrange false, Hidden, minimal switcher"); + assert_eq!(safe(71.0), "community false, learn false, arrange false, Hidden, no switcher"); } /// What screen readers call the app bar's search field, and the icon it becomes, before the shortcut. @@ -897,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. @@ -1914,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) { @@ -4651,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/community.rs b/crates/ui-egui/src/community.rs index 034807b8b7..97f7dffdba 100644 --- a/crates/ui-egui/src/community.rs +++ b/crates/ui-egui/src/community.rs @@ -33,7 +33,7 @@ pub fn discord_button(app: &mut VectorcraftApp, ui: &mut Ui, large: bool) -> egu let ir = egui::Rect::from_center_size(r.left_center() + vec2(h * 0.35 + icon / 2.0, 0.0), vec2(icon, icon)); if large { // The theme's accent, as the primary buttons use it, so the call to action matches the - // rest of the window (and PhotoCraft's, #4684); Discord's colour stays on the app-bar icon. + // rest of the window (#4684); Discord's colour stays on the app-bar icon. let t = Tokens::get(ui.ctx()); let fill = if resp.hovered() { t.accent } else { t.accent_strong }; ui.painter().rect_filled(r, CornerRadius::same((h / 2.0) as u8), fill); @@ -77,7 +77,7 @@ pub fn links(app: &mut VectorcraftApp, ui: &mut Ui) { links_in(app, ui, false); } -/// [`links`] for a centred column (the Home screen's, as PhotoCraft's, #4684): the Discord button +/// [`links`] for a centred column (the Home screen's, #4684): the Discord button /// and the links, each in the middle. pub fn links_centered(app: &mut VectorcraftApp, ui: &mut Ui) { links_in(app, ui, true); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a2c29fadc4..b5b829ebbf 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -240,6 +240,7 @@ fn wrap(r: Result) -> Outcome { pub fn all_commands(app: &VectorcraftApp) -> Value { let mut v: Vec = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); for (id, label, sc, params) in crate::menus::UI_COMMANDS { + let sc = crate::shortcut_editor::ui_command_default(id, sc, crate::keymap::platform()); v.push(json!({"id": id, "label": label, "shortcut": sc, "params": params, "enabled": crate::menus::enabled(app, id), "ui": true})); } Value::Array(v) @@ -274,11 +275,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), - // Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew: - // each one's document index, view number (Window › New Window) and rect. Canvas - // coordinates map to the current window's pane, inside its rulers and scroll bars + // Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the + // last frame drew: each one's document index, view number (Window › New Window) and rect. + // Canvas coordinates map to the current window's pane, inside its rulers and scroll bars // (`canvasRect`). "tiled": app.ui.tiled, + "tileLayout": app.ui.tile_layout.name(), "panes": app.canvas.panes.last.iter().map(|(w, c)| json!({ "document": w.0, "view": w.1, @@ -1607,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(); @@ -2105,7 +2109,7 @@ fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { r = app.run("window.panel", json!({"panel": pn})); } if let Some(st) = s("status") { - app.ui.status = st.to_string(); + app.status(st); } for (k, flag) in [ ("rulers", "view.rulers"), diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 7aa73e8a7e..96c4880d39 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -1426,3 +1426,19 @@ fn dialog_set_refuses_a_field_the_dialog_does_not_have() { app.ui.dialog = None; assert_eq!(input_request(&mut app, "ui.dialog.set", json!({"field": "name", "value": "A"}))["error"], "no dialog open"); } + +/// `engine.commands` lists each UI command's default shortcut on this platform: Select Last +/// Selection Tool shows Ctrl+` (`Cmd+~`) on Windows and Linux and none on macOS. +#[test] +fn the_command_list_shows_this_platforms_default_shortcut() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let r = input_request(&mut app, "engine.commands", json!({})); + let row = r["result"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned(); + let row = row.unwrap_or_else(|| panic!("listed: {r}")); + assert_eq!(row["shortcut"], if crate::keymap::platform().is_mac() { "" } else { "Cmd+~" }, "{row}"); + for p in [craft_keymap::Platform::Windows, craft_keymap::Platform::Linux] { + assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", p), "Cmd+~", "{p:?}"); + } + assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", craft_keymap::Platform::Mac), ""); + assert_eq!(crate::shortcut_editor::ui_command_default("view.zoomIn", "Cmd+=", craft_keymap::Platform::Mac), "Cmd+="); +} diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 4db2e5cb45..83db707642 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -1,5 +1,5 @@ //! Tool cursors drawn as vector glyphs (egui only offers system cursors). Black shapes with a white -//! halo, hotspot at `p`, Illustrator's visual grammar: solid arrow (Selection), hollow arrow (Direct +//! halo, hotspot at `p`, one shape per tool: solid arrow (Selection), hollow arrow (Direct //! Selection), pen nib with state badges, crosshair for drawing tools, curved arrows for rotate. //! //! The desktop app shows them as OS cursors ([`Images`]): the system moves those itself, at once, diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index f8c3033a5e..fcbee2132a 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 9e54eb12f6..37781291ec 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -15,6 +15,7 @@ pub mod action_select_object; pub mod action_set_options; pub mod action_stop; pub mod artboard_options; +pub mod attributes_panel_options; pub mod blend_options; mod brush_art_options; pub mod brush_delete; @@ -25,7 +26,7 @@ pub mod char_style_options; pub mod check_spelling; pub mod color_balance; pub mod color_guide_options; -mod color_picker; +pub(crate) mod color_picker; mod command; pub mod composite_fonts; pub mod confirm; @@ -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; @@ -60,6 +62,7 @@ pub mod graph_design; pub mod graph_type; pub mod graphic_style_options; pub mod halftone; +pub mod hpgl_options; pub mod hyphenation; pub mod import_pdf; pub mod indexed_color; @@ -80,6 +83,7 @@ pub mod new_color_group; mod new_document; pub mod new_swatch; pub mod new_text_style; +pub mod object_mosaic; pub mod objects_on_path_options; pub mod office_export; pub mod package; @@ -167,7 +171,7 @@ pub(crate) use export_for_screens::{ open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, saved_options as screen_saved_options, saved_rows as screen_saved_rows, settings_format as screen_settings_format, }; -pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix}; +pub(crate) use form::{humanize, number_list_text, plugin_color_button, ppi_suffix, read_number_list, unit_suffix}; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; pub(crate) use new_document::{popup_open as new_document_popup_open, preset_name}; pub use png_options::open as open_raster_options; @@ -343,6 +347,7 @@ registry! { ReplaceFiles: [confirm::REPLACE_FILES] => confirm::REPLACE_FILES_SPEC, ResetPreferences: [confirm::RESET_PREFS] => confirm::RESET_PREFS_SPEC, ResetActions: [confirm::RESET_ACTIONS] => confirm::RESET_ACTIONS_SPEC, + MissingFontEdit: [confirm::MISSING_FONT_EDIT] => confirm::MISSING_FONT_EDIT_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC, GraphData: [graph_data::KIND] => graph_data::SPEC, @@ -398,6 +403,7 @@ registry! { MissingLinks: [missing_links::KIND] => missing_links::SPEC, MissingFonts: [missing_fonts::KIND] => missing_fonts::SPEC, FindLinks: [find_links::KIND] => find_links::SPEC, + FindReplace: [find_replace::KIND] => find_replace::SPEC, TextImport: [text_import::KIND] => text_import::SPEC, PdfPresets: [pdf_presets::KIND] => pdf_presets::SPEC, PdfPreset: [save_pdf::PRESET_KIND] => save_pdf::PRESET_SPEC, @@ -419,6 +425,8 @@ registry! { SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, + EpsFlattenerOptions: [eps_options::CUSTOM_KIND] => eps_options::CUSTOM_SPEC, + HpglOptions: [hpgl_options::KIND] => hpgl_options::SPEC, Recovery: [crate::recovery::KIND] => recovery::SPEC, PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC, SafeMode: [safe_mode::KIND] => safe_mode::SPEC, @@ -439,7 +447,9 @@ registry! { ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, 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, @@ -470,12 +480,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, @@ -537,15 +549,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. @@ -597,7 +610,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); @@ -608,18 +622,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); } @@ -646,6 +672,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"; @@ -656,18 +692,31 @@ pub(crate) fn parent(d: &Dialog) -> Option { } /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields -/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change +/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`, EPS Options' +/// `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, and Transform Each's Relative / Absolute keeps the Scale fields' size. A value -/// Composite Fonts' Show Sample can't take is refused. +/// 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. 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); return Ok(()); } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == recolor::KIND) { + return recolor::field_set(app, field); + } 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(()); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), @@ -699,6 +748,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == safe_mode::STOPPED { safe_mode::cancel_stopped(app); } + if d.kind == confirm::MISSING_FONT_EDIT { + confirm::answer_missing_font_edit(app, &d, false); + } // The growth question's Cancel button is its Stop button. if d.kind == script_run::GROWTH_KIND { app.session.script_request_stop(); @@ -706,6 +758,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::NOTICE_KIND { script_run::notice_cancel(app, &d); } + if d.kind == script_run::PICKER_KIND { + script_run::picker_cancel(app, &d); + } missing_links::cancelled(app, &d); // Find Font's next open starts with an empty replacement search. if d.kind == "findFont" @@ -817,6 +872,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); } @@ -832,6 +891,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if after_panel && !ctx.input(|i| i.key_down(egui::Key::Enter) || i.key_pressed(egui::Key::Enter)) { d.fields.remove(AFTER_PANEL); } + // A body can open another dialog in its place (EPS Options' Custom…): this frame's Enter + // doesn't confirm that one. + let opened = d.kind.clone(); let heading = (spec.heading)(&d); let revolves = revolve_gizmo::active(&d); if revolves { @@ -856,14 +918,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() { @@ -931,7 +995,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if ok_clicked && !rejected && !refused_during_click { ok = true; } - if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) { + if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && d.kind == opened && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) { ok = true; } if discard { @@ -997,6 +1061,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)] @@ -1042,6 +1108,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 8bc0e66a2e..308b3a9eb9 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 { @@ -254,7 +255,8 @@ fn scatter_mode(d: &Dialog, key: &str) -> Variation { Variation::parse(&d.str(&mode_key(key))).unwrap_or_default() } -/// How an art brush's width varies: Fixed, or with the pen's pressure, tilt, bearing or rotation. +/// How an art brush's width varies: Fixed, or with the pen's pressure, tilt, bearing, rotation or +/// wheel. fn art_width_mode(d: &Dialog) -> Variation { Variation::parse(&d.str("widthMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) } @@ -268,6 +270,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" => { @@ -434,7 +437,6 @@ fn flips(ui: &mut egui::Ui, d: &mut Dialog) { fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { let labels = [tl!("Size:"), tl!("Spacing:"), tl!("Scatter:"), tl!("Rotation:")]; - let modes = Variation::ALL.map(Variation::label); egui::Grid::new("brush-options-scatter").num_columns(4).spacing([8.0, 8.0]).show(ui, |ui| { for (((key, suffix), range), text) in SCATTER.into_iter().zip(Scatter::RANGES).zip(labels) { super::swatch_options::label(ui, text); @@ -448,7 +450,9 @@ fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { } }); } - if let Some(m) = widgets::dropdown(ui, ("brush-scatter-mode", key), mode.label(), &modes, 104.0).and_then(|i| Variation::ALL.get(i)) { + let offered = Variation::offered(key == "size"); + let modes: Vec<&str> = offered.iter().map(|m| m.label()).collect(); + if let Some(m) = widgets::dropdown(ui, ("brush-scatter-mode", key), mode.label(), &modes, 104.0).and_then(|i| offered.get(i)) { d.fields.insert(mode_key(key), json!(m.id())); } ui.end_row(); @@ -457,6 +461,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) { @@ -467,11 +474,18 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { super::form::slider_field_named(ui, d, "width", tl!("Width:"), range.0..=range.1, "%", &|_| rail); let mode = art_width_mode(d); number(ui, d, "widthMax", range, "%", mode.follows_pen()); - let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation]; + let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; if let Some(m) = widgets::dropdown(ui, "brush-art-width-mode", mode.label(), &modes.map(Variation::label), 104.0).and_then(|i| modes.get(i)) { d.fields.insert("widthMode".into(), json!(m.id())); } }); + // A path sets its own width, flips, overlap and colorization, not how the art scales or runs. + if d.bool(super::brush_options::OBJECT) { + flips(ui, d); + ui.add_space(4.0); + super::form::check(ui, d, "overlap", tl!("Overlap")); + return; + } ui.add_space(4.0); widgets::section_header(ui, tl!("Brush Scale Options")); let scales = [ @@ -532,8 +546,11 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { slider_row(ui, d, "scale", tl!("Scale:"), PatternBrush::SCALE_RANGE); widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| number(ui, d, "spacing", PatternBrush::SPACING_RANGE, "%", true)); ui.add_space(6.0); - tiles(ui, d); - ui.add_space(6.0); + // The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization. + if !d.bool(super::brush_options::OBJECT) { + tiles(ui, d); + ui.add_space(6.0); + } flips(ui, d); widgets::section_header(ui, tl!("Fit")); let fits = [("stretch", tl!("Stretch to fit")), ("addSpace", tl!("Add space to fit")), ("approximate", tl!("Approximate path"))]; diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index bcc880958a..f8b25e8249 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -17,10 +17,18 @@ //! New Brush opens the dialog for a brush that does not exist yet ([`open_new`]), with `__create` //! and, for dropped art, `__ids`: OK runs `brush.new` instead, which gives a name another brush has //! a number, and Cancel adds nothing. +//! +//! The panel menu's Options of Selected Object opens the dialog on the brush of the first selected +//! brushed path, with that path's own settings ([`open_object`]), with `__object`, `__targets` (the +//! brushed paths), `__opened` (the values it opened with) and `__doc` (the uid of the document). It +//! has no name, and of the Art and Pattern brush options only those a path can set for itself. OK +//! runs `brush.objectOptions` with the values changed since it opened: the paths change and the +//! brush stays as it is. OK after another document has become the active one changes nothing. use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{Bristle, Brush, BrushKind, Calligraphic, Variation}; +use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; use super::swatch_options::{grid, label}; use super::{DialogSpec, brush_art_options, form}; @@ -39,6 +47,18 @@ const CREATE: &str = "__create"; /// The field of such a dialog holding the ids of the art dropped on the Brushes panel. const IDS: &str = "__ids"; +/// The field of a Brush Options dialog that Options of Selected Object opened. +pub(super) const OBJECT: &str = "__object"; + +/// The field of such a dialog holding the brushed paths it sets. +const TARGETS: &str = "__targets"; + +/// The field of such a dialog holding the `brush.objectOptions` params it opened with. +const OPENED: &str = "__opened"; + +/// The field of such a dialog holding the uid of the document it opened in. +const DOC: &str = "__doc"; + /// Calligraphic values: (field, label, suffix, decimals), in [`Calligraphic::RANGES`] order. const CALLI: [(&str, &str, &str, usize); 3] = [("angle", "Angle:", "°", 0), ("roundness", "Roundness:", "%", 0), ("size", "Size:", " pt", 1)]; @@ -73,6 +93,9 @@ const NIB_W: f32 = 120.0; const STROKE_W: f32 = 400.0; fn heading(d: &Dialog) -> String { + if d.bool(OBJECT) { + return tl!("Options of Selected Object").into(); + } match d.str("__type").as_str() { "bristle" => tl!("Bristle Brush Options").into(), "calligraphic" => tl!("Calligraphic Brush Options").into(), @@ -146,6 +169,118 @@ fn target(app: &VectorcraftApp) -> Option { selected.or_else(|| vectorcraft_brush::current(&st.doc)) } +/// The brush that the first brushed stroke of path `id` paints with, in library `lib`. +fn stroke_brush<'a>(app: &VectorcraftApp, lib: &'a [Brush], id: NodeId) -> Option<&'a Brush> { + let n = app.session.active()?.doc.node(id)?; + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Stroke(st) => st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)), + AppearanceItem::Fill(_) => None, + }) +} + +/// Can Options of Selected Object open: does a selected path or compound path (or one in a +/// selected group, but not a path inside a compound path, as `brush.objectOptions` takes them) +/// paint with a brush, are all their brushes of one type, and can a path set options of its own +/// for that type? These are the selections `brush.objectOptions` takes. +pub fn object_available(app: &VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let ids = st.selection.subjects(); + if ids.is_empty() { + return false; + } + let lib = vectorcraft_brush::library(&st.doc); + let doc = &st.doc; + // The brush of every brushed stroke of the paths the command sets. + let mut brushes: Vec<&Brush> = vec![]; + for id in ids { + let Some(n) = doc.node(*id) else { continue }; + n.walk(&mut |c| { + let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); + let in_compound = doc.parent_of(c.id).and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if !own || in_compound { + return; + } + for i in &c.appearance.items { + if let AppearanceItem::Stroke(s) = i + && let Some(b) = s.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) + { + brushes.push(b); + } + } + }); + } + let Some(first) = brushes.first() else { return false }; + !first.kind.stroke_option_keys().is_empty() && brushes.iter().all(|b| b.kind.type_id() == first.kind.type_id()) +} + +/// Open Options of Selected Object: the Brush Options of the brush the first selected brushed path +/// paints with, at that path's own settings, without the name and with only the options a path can +/// set for itself. +pub fn open_object(app: &mut VectorcraftApp) -> Result { + let r = app.run("brush.objectOptions", json!({}))?; + let targets = r["ids"].clone(); + let first = targets.get(0).and_then(Value::as_u64).map(NodeId).ok_or("no path painted with a brush is selected")?; + let st = app.session.active().ok_or("no document open")?; + let (lib, doc) = (vectorcraft_brush::library(&st.doc), st.uid); + let b = stroke_brush(app, &lib, first).ok_or("no path painted with a brush is selected")?; + let own: Map = serde_json::from_value(r["options"].clone()).unwrap_or_default(); + let edited = b.with_stroke_options(&own)?; + let def = serde_json::to_value(&edited).map_err(|e| e.to_string())?; + let mut f = fields(&edited, def)?; + f.insert("__brush".into(), json!(b.name)); + f.insert(OBJECT.into(), json!(true)); + f.insert(TARGETS.into(), targets); + f.insert(DOC.into(), json!(doc)); + let mut d = Dialog { kind: KIND.into(), fields: f }; + let opened = object_params(&d, b.kind.stroke_option_keys()); + d.fields.insert(OPENED.into(), Value::Object(opened)); + d.fields.insert("__keys".into(), json!(b.kind.stroke_option_keys())); + app.ui.dialog = Some(d); + Ok(Value::Null) +} + +/// The fields' `brush.options` params that a path can set for itself (`keys`). +fn object_params(d: &Dialog, keys: &[&str]) -> Map { + match params(d) { + Value::Object(p) => p.into_iter().filter(|(k, _)| keys.contains(&k.as_str())).collect(), + _ => Map::new(), + } +} + +/// What of option value `now` changed from `was`, the value it opened with: `None` when nothing +/// did; of a range or a list of modes, the items that changed with `null` for the others, and of a +/// colorization, the fields that changed. The paths keep their own values for the rest. +fn changed_part(was: Option<&Value>, now: Value) -> Option { + match (was, now) { + (Some(w), n) if *w == n => None, + (Some(Value::Array(w)), Value::Array(n)) if w.len() == n.len() => { + Some(Value::Array(w.iter().zip(n).map(|(w, n)| if *w == n { Value::Null } else { n }).collect())) + } + (Some(Value::Object(w)), Value::Object(n)) => Some(Value::Object(n.into_iter().filter(|(f, v)| w.get(f) != Some(v)).collect())), + (_, n) => Some(n), + } +} + +/// OK of Options of Selected Object: `brush.objectOptions` on the paths it opened for, with the +/// values changed since it opened ([`changed_part`]). The dialog closes when they are set. When +/// another document has become the active one, it closes as Cancel does and changes nothing. +fn confirm_object(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } + let keys: Vec = d.fields.get("__keys").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); + let opened = d.fields.get(OPENED).and_then(Value::as_object).cloned().unwrap_or_default(); + let changed: Map = + object_params(d, &keys).into_iter().filter_map(|(k, v)| changed_part(opened.get(&k), v).map(|v| (k, v))).collect(); + let r = app.run("brush.objectOptions", json!({ "ids": d.fields.get(TARGETS).cloned().unwrap_or_default(), "params": changed })); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// Open the Brush Options of a new brush of type `ty` (`calligraphic` | `scatter` | `art` | /// `bristle` | `pattern`), the second step of New Brush. The fields start from the type's default /// values and the name "New Brush", numbered when another brush has it. A scatter or art @@ -240,7 +375,13 @@ fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result { /// OK: make the new brush when New Brush opened the dialog, else edit the brush. fn ok(app: &mut VectorcraftApp, d: &Dialog) -> Result { - if d.bool(CREATE) { create(app, d) } else { confirm(app, d) } + if d.bool(CREATE) { + create(app, d) + } else if d.bool(OBJECT) { + confirm_object(app, d) + } else { + confirm(app, d) + } } /// The value of field `key` within `range`. @@ -279,13 +420,16 @@ fn params(d: &Dialog) -> Value { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - grid(ui, |ui| { - label(ui, tl!("Name:")); - let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; - form::text_edit_limited(ui, d, "name", 240.0, max); - ui.end_row(); - }); - ui.add_space(10.0); + // Options of Selected Object sets a path's settings, not the brush, so it has no name. + if !d.bool(OBJECT) { + grid(ui, |ui| { + label(ui, tl!("Name:")); + let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; + form::text_edit_limited(ui, d, "name", 240.0, max); + ui.end_row(); + }); + ui.add_space(10.0); + } match d.str("__type").as_str() { "bristle" => bristle_body(app, ui, d), "calligraphic" => calligraphic_body(app, ui, d), @@ -310,8 +454,9 @@ fn calligraphic_body(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert(key.into(), json!(v)); } let mode = Variation::parse(&d.str(&mode_key(key))).unwrap_or_default(); - let labels = Variation::ALL.map(Variation::label); - if let Some(m) = widgets::dropdown(ui, ("brush-mode", key), mode.label(), &labels, 104.0).and_then(|i| Variation::ALL.get(i)) { + let offered = Variation::offered(key == "size"); + let labels: Vec<&str> = offered.iter().map(|m| m.label()).collect(); + if let Some(m) = widgets::dropdown(ui, ("brush-mode", key), mode.label(), &labels, 104.0).and_then(|i| offered.get(i)) { d.fields.insert(mode_key(key), json!(m.id())); } label(ui, tl!("Variation:")); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index df45452a02..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] @@ -883,3 +887,160 @@ fn art_width_and_pattern_scale_have_sliders() { let shown = tree(|ui| super::super::show(&mut app, ui.ctx())); assert_eq!(slider_value(&shown, "Scale:"), (Some(100.0), Some(1.0), Some(10000.0), Some("100%".into()))); } + +/// A level line, selected, painted with brush `brush`. +fn brushed_line(app: &mut VectorcraftApp, y: f64, brush: &str) -> u64 { + let id = app.run("shape.line", json!({"x1": 20, "y1": y, "x2": 220, "y2": y})).unwrap()["id"].as_u64().unwrap(); + app.run("brush.apply", json!({"name": brush, "ids": [id]})).unwrap(); + id +} + +/// The own brush settings of the first stroke of path `id`. +fn own_options(app: &VectorcraftApp, id: u64) -> Value { + let st = app.session.active().unwrap().doc.node(NodeId(id)).and_then(|n| n.appearance.stroke().cloned()).unwrap(); + Value::Object(st.brush_options) +} + +fn select(app: &mut VectorcraftApp, ids: &[u64]) { + app.run("select.set", json!({ "ids": ids })).unwrap(); +} + +#[test] +fn options_of_selected_object_set_one_paths_art_brush_settings() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Arrow"); + let b = brushed_line(&mut app, 100.0, "Arrow"); + select(&mut app, &[a]); + assert!(object_available(&app)); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Options of Selected Object", "Width:", "Flip Along", "Flip Across", "Overlap", "Colorization", "OK"] { + assert!(text.contains(label), "{label} in {text}"); + } + for label in ["Name:", "Brush Scale Options", "Direction:"] { + assert!(!text.contains(label), "{label} in {text}"); + } + set(&mut app, json!({"width": 50})); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(own_options(&app, a), json!({"width": 50.0})); + assert_eq!(own_options(&app, b), json!({})); + assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(100.0), "the brush keeps its width"); + // Opened again, it shows the path's own width, and OK without a change changes nothing. + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("width", 0.0), 50.0); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"width": 50.0})); +} + +#[test] +fn options_of_selected_object_change_only_the_values_edited_on_each_path() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Confetti"); + let b = brushed_line(&mut app, 100.0, "Confetti"); + app.run("brush.objectOptions", json!({"ids": [a], "params": {"size": [50, 80]}})).unwrap(); + app.run("brush.objectOptions", json!({"ids": [b], "params": {"size": [60, 120]}})).unwrap(); + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + // The dialog shows the first path's values; only the smallest size is edited. + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("sizeMax", 0.0), 80.0); + set(&mut app, json!({"sizeMin": 40})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a)["size"], json!([40.0, 80.0])); + assert_eq!(own_options(&app, b)["size"], json!([40.0, 120.0]), "the second path keeps its own largest size"); +} + +/// The modes the first stroke of path `id` draws its brush `brush` with. +fn drawn_modes(app: &VectorcraftApp, id: u64, brush: &str) -> Vec { + let lib = vectorcraft_brush::library(&app.session.active().unwrap().doc); + let b = lib.iter().find(|b| b.name == brush).unwrap(); + let own = own_options(app, id); + match b.with_stroke_options(own.as_object().unwrap()).unwrap().kind { + BrushKind::Calligraphic(c) => c.modes().to_vec(), + BrushKind::Scatter(s) => s.modes().to_vec(), + _ => vec![], + } +} + +#[test] +fn options_of_selected_object_keep_the_modes_they_show_when_a_value_changes() { + let mut app = app(); + // Confetti's size varies at random from 60% to 140%; a size of 60% to 60% leaves the mode the + // dialog shows. + let s = brushed_line(&mut app, 50.0, "Confetti"); + select(&mut app, &[s]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("sizeMode"), "random"); + set(&mut app, json!({"sizeMax": 60})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, s)["size"], json!([60.0, 60.0])); + assert_eq!(drawn_modes(&app, s, "Confetti")[0], Variation::Random); + // 6 pt. Flat's angle is Fixed; a variation set without a mode keeps it Fixed. + let c = brushed_line(&mut app, 100.0, "6 pt. Flat"); + select(&mut app, &[c]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("angleMode"), "fixed"); + set(&mut app, json!({"angleVariation": 30})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(drawn_modes(&app, c, "6 pt. Flat")[0], Variation::Fixed); +} + +#[test] +fn options_of_selected_object_show_what_a_path_can_set_for_each_type() { + let mut app = app(); + // Calligraphic: OK without a change leaves the path on the brush's settings. + let c = brushed_line(&mut app, 40.0, "6 pt. Flat"); + select(&mut app, &[c]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Angle:", "Roundness:", "Size:"] { + assert!(text.contains(label), "{label} in {text}"); + } + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, c), json!({})); + // Pattern: scale, spacing, flips and fit, not the tiles. + let p = brushed_line(&mut app, 80.0, "Diamonds"); + select(&mut app, &[p]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Scale:", "Spacing:", "Fit", "Flip Along"] { + assert!(text.contains(label), "{label} in {text}"); + } + assert!(!text.contains("Side Tile"), "{text}"); + set(&mut app, json!({"scale": 200})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, p), json!({"scale": 200.0})); + // Bristle brushes, nothing selected and two brush types are refused. + let r = brushed_line(&mut app, 120.0, "Bristle Round"); + select(&mut app, &[r]); + assert!(!object_available(&app)); + assert!(app.run("ui.brushObjectOptions", json!({})).is_err()); + select(&mut app, &[c, p]); + assert!(!object_available(&app), "the menu item is off for two brush types"); + assert!(app.run("ui.brushObjectOptions", json!({})).is_err()); + assert!(app.ui.dialog.is_none()); + select(&mut app, &[p, r]); + assert!(!object_available(&app), "the menu item is off for a pattern and a bristle brush"); + app.run("select.none", json!({})).unwrap(); + assert!(!object_available(&app)); +} + +#[test] +fn options_of_selected_object_change_nothing_after_another_document_became_active() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Arrow"); + select(&mut app, &[a]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"width": 50})); + // A second document with a brushed path of the same id becomes the active one. + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = brushed_line(&mut app, 50.0, "Arrow"); + assert_eq!(other, a); + // OK closes the dialog as Cancel does. + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(own_options(&app, other), json!({}), "the second document's path keeps the brush's settings"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(own_options(&app, a), json!({}), "the first document's path keeps the brush's settings"); +} diff --git a/crates/ui-egui/src/dialogs/brush_replace_art.rs b/crates/ui-egui/src/dialogs/brush_replace_art.rs index cc1a08b251..f1ebf1083f 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art.rs @@ -44,7 +44,7 @@ pub fn replace(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { return; } // A preview on a copy of the document checks the art without changing anything. - if !app.session.in_interaction() && app.session.begin_interaction("Replace Brush Art").is_ok() { + if !app.session.in_interaction() && app.begin_interaction("Replace Brush Art").is_ok() { let checked = app.session.preview("brush.replaceArt", ¶ms); // The interaction began above, on the active document: ending it puts that document back // as it was, and can fail only when no document is open, when there is nothing to put back. diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 43f15edbb8..3eb9b38547 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -12,14 +12,20 @@ //! preset picked), `bullet` (`dot`, `dash`, `circle` or `square`), `number` (`arabic`, //! `upperLetters`, `lowerLetters`, `upperRoman`, `lowerRoman`, `twoDigits` or `threeDigits`), //! `listAlign` (`left` or `right`), `listLevel` (1 to 9; 1 for paragraphs in no list), -//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, with `__initial` (the -//! values it opened with) and `__targets` (the type and range it acts on). +//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, `startAt` (the Numbers +//! tab's Start At box) and `startNumber` (its number, 1 to 999999999), with `__initial` (the values +//! it opened with) and `__targets` (the type and range it acts on). +//! +//! Start At is VectorCraft's own: on, OK gives the first numbered paragraph the number in the +//! field (`text.setFormat` `startNumber`), and the numbered paragraphs after it count on from it; +//! off, the paragraphs count on from the paragraph before (`restartNumbering` false). The box is on +//! when the paragraphs have a number of their own, off when none has, and blank when they differ. //! //! Behavior reference (public documentation): //! . use serde_json::{Map, Value, json}; -use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, NumberStyle, ParaList}; +use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList}; use super::swatch_options::label; use super::{DialogSpec, form}; @@ -52,7 +58,7 @@ const ARROWS: egui::EventFilter = egui::EventFilter { tab: false, horizontal_arr /// The fields `ui.dialog.set` can set while the dialog does not hold them: the dialog leaves a /// field out where the paragraphs differ, and holds no `bullet` or `number` for paragraphs in no /// list or in another kind of list. -const INPUTS: [&str; 7] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent"]; +const INPUTS: [&str; 9] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent", "startAt", "startNumber"]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Bullets and Numbering").into(), @@ -85,8 +91,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); - if let Some((id, a, b)) = crate::panels::character::text_editing(app) { - crate::panels::character::end_typing(app); + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { targets = json!({"ids": [id.0], "start": a, "end": b}); } let mut values = Map::new(); @@ -114,6 +119,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if let Some(v) = shared_para_field(app, |p| p.first_line_indent) { values.insert("firstLineIndent".into(), json!(v)); } + // …and Start At: on with the number when the paragraphs share one, off when none has one. + if let Some(start) = shared_para(app, |p| p.list.and_then(|l| l.start)) { + values.insert("startAt".into(), json!(start.is_some())); + if let Some(n) = start { + values.insert("startNumber".into(), json!(n)); + } + } let tab = tab.unwrap_or(if list == Some("number") { "numbers" } else { "bullets" }); let mut fields = Value::Object(values.clone()); fields[INITIAL] = Value::Object(values); @@ -210,6 +222,29 @@ fn number_tab(ui: &mut egui::Ui, d: &mut Dialog) { } None => {} } + ui.add_space(8.0); + start_at(ui, d); +} + +/// The Start At box and its number, 1 to [`MAX_LIST_START`]: the box shows a dash while the +/// paragraphs' numbers differ, and a click then turns it on; the number field is dimmed unless the +/// box is on, and shows 1 until a number is typed. +fn start_at(ui: &mut egui::Ui, d: &mut Dialog) { + ui.horizontal(|ui| { + let on = d.fields.get("startAt").and_then(Value::as_bool); + if widgets::check3(ui, tl!("Start at:"), on, true) { + d.fields.insert("startAt".into(), json!(on != Some(true))); + } + let value = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + ui.add_enabled_ui(on == Some(true), |ui| { + let name = Some(tl!("Start at:")); + if let Some(v) = + widgets::range_field_named(ui, ("bullets-numbering", "startNumber"), name, value, 1.0..=f64::from(MAX_LIST_START), "", 0, 90.0) + { + d.fields.insert("startNumber".into(), json!(v)); + } + }); + }); } /// A row of preset buttons named `names`, `current` selected, each drawn by `paint` (painter, @@ -367,6 +402,20 @@ fn params(d: &Dialog) -> Map { { p.insert("listLevel".into(), json!(l)); } + // …and Start At, unless the paragraphs are made bulleted or taken out of their list: on, the + // number shown; off, the paragraphs count on from the one before. + if let Some(on) = d.fields.get("startAt").and_then(Value::as_bool) + && !matches!(field("list"), Some("none" | "bullet")) + { + let n = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + let was_on = initial.and_then(|m| m.get("startAt")).and_then(Value::as_bool); + let was_n = initial.and_then(|m| m.get("startNumber")).and_then(Value::as_f64); + if on && (was_on != Some(true) || was_n != Some(n)) { + p.insert("startNumber".into(), json!(n)); + } else if !on && was_on != Some(false) { + p.insert("restartNumbering".into(), json!(false)); + } + } // For paragraphs in a list and paragraphs in none, an indent left as it was is not sent: // `text.setFormat` then gives each paragraph that joins the list its hanging indent. let mixed = initial.is_some_and(|m| !m.contains_key("list")); @@ -690,7 +739,8 @@ mod tests { app.run("text.setFormat", json!({"ids": [id], "listAlign": "right", "listLevel": 2, "start": 0, "end": 0})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); let held = app.ui.dialog.as_ref().unwrap().fields.clone(); - for key in INPUTS { + // Neither paragraph has a number of its own, so Start at is off, not blank. + for key in INPUTS.into_iter().filter(|k| !["startAt", "startNumber"].contains(k)) { assert!(!held.contains_key(key), "{key} is blank"); } let fields = json!([ @@ -737,6 +787,67 @@ mod tests { assert_eq!((first(&app, id).0.map(|l| l.level), paras(&app, id).1.list.map(|l| l.level)), (Some(2), Some(2))); } + /// Start at: the box opens off for paragraphs without a number of their own and on with the + /// number for one that has it; a change shows on the type at once, OK keeps it as one undo + /// step, Cancel puts the type back, and turning the box off sends `restartNumbering` false. + #[test] + fn start_at_gives_the_first_numbered_paragraph_its_number() { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"number": "arabic"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields.get("startAt"), d.fields.get("startNumber")), (Some(&json!(false)), None)); + set(&mut app, "startAt", json!(true)); + set(&mut app, "startNumber", json!(4)); + frame(&mut app); + let starts = |app: &VectorcraftApp| { + let (one, two) = paras(app, id); + (one.list.and_then(|l| l.start), two.list.and_then(|l| l.start)) + }; + assert_eq!(starts(&app), (Some(4), None), "previewed on the type"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the preview adds no undo step"); + super::super::cancel(&mut app); + assert_eq!(starts(&app), (None, None), "Cancel puts it back"); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + set(&mut app, "startAt", json!(true)); + set(&mut app, "startNumber", json!(4)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((starts(&app), app.session.active().unwrap().history.undo.len()), ((Some(4), None), undo + 1)); + // One paragraph with a number and one without: the box is blank, and OK sends nothing for it. + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert!(!d.fields.contains_key("startAt") && !changes(¶ms(&d))); + // The blank box shows a dash, not an empty box. + use egui::accesskit::{Role, Toggled}; + let mut shown = d.clone(); + let tree = crate::widgets::accessibility_tests::tree(|ui| start_at(ui, &mut shown)); + let check = tree.iter().find(|n| n.label() == Some("Start at:") && n.role() == Role::CheckBox).map(|n| n.toggled()); + assert_eq!(check, Some(Some(Toggled::Mixed))); + // A preset that makes the paragraphs bulleted sends no number. + set(&mut app, "startAt", json!(true)); + pick_preset(&mut app, "bullet", Some("dot")); + let p = params(app.ui.dialog.as_ref().unwrap()); + assert!(!p.contains_key("startNumber") && !p.contains_key("restartNumbering")); + super::super::cancel(&mut app); + // A paragraph with a number opens the box on with it, and off sends it back to counting on. + let solo = app.run("text.create", json!({"x": 10, "y": 200, "text": "Solo"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [solo]})).unwrap(); + app.run("text.setFormat", json!({"number": "arabic", "startNumber": 9})).unwrap(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields.get("startAt"), d.f64("startNumber", 0.0)), (Some(&json!(true)), 9.0)); + assert!(!changes(¶ms(&d)), "nothing changed yet"); + set(&mut app, "startAt", json!(false)); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()).get("restartNumbering"), Some(&json!(false))); + super::super::confirm(&mut app).unwrap(); + let start = match &app.session.active().unwrap().doc.node(NodeId(solo)).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).list.map(|l| l.start), + _ => panic!("not text"), + }; + assert_eq!(start, Some(None), "still numbered, with no number of its own"); + } + /// `text.setFormat` sets `listLevel` only on paragraphs in a list, so a Level change alone on /// paragraphs in no list sends nothing and adds no undo step; with a preset it applies. #[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 f86ee17f51..758832cd92 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -103,11 +103,22 @@ impl Channel { Channel::Green => "G", } } - fn is_hsb(self) -> bool { + /// The channel's name, translated: Hue, Saturation, Brightness, Red, Green or Blue. + pub(crate) fn name(self) -> &'static str { + match self { + Channel::Hue => tl!("Hue"), + Channel::Saturation => tl!("Saturation"), + Channel::Brightness => tl!("Brightness"), + Channel::Red => tl!("Red"), + Channel::Green => tl!("Green"), + Channel::Blue => tl!("Blue"), + } + } + pub(crate) fn is_hsb(self) -> bool { matches!(self, Channel::Hue | Channel::Saturation | Channel::Brightness) } /// Indices of (slider, field x, field y) into the channel's space: [h, s, b] or [r, g, b]. - fn axes(self) -> (usize, usize, usize) { + pub(crate) fn axes(self) -> (usize, usize, usize) { match self { Channel::Hue => (0, 1, 2), Channel::Saturation => (1, 0, 2), @@ -119,7 +130,7 @@ impl Channel { } /// The color field's axes (across, up) as keys and screen readers see them: hue in degrees, /// saturation and brightness in percent, red, green and blue from 0 to 255. - fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] { + pub(crate) fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] { let axis = |i: usize| { let (name, units, suffix) = match (self.is_hsb(), i) { (true, 0) => (tl!("Hue"), 360.0, "°"), @@ -282,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 } @@ -360,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 }; @@ -406,10 +431,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let track = |z: f32| c32(&Picked::of(slider_color(channel, z, x, y)).snapped(web).color); let (v, suffix, max) = channel_value(channel, &p); let shown = widgets::SliderValue::field(v as f64, 0.0..=max as f64, suffix, 0); - if let (Some(z), _) = - widgets::channel_slider_valued(ui, "cp-slider", tl!(channel.label()), Some(shown), z, vec2(SLIDER_W, side), &track) - { - pick = Some(field_pick(channel, z, x, y)); + match widgets::channel_slider_stepped( + ui, + "cp-slider", + tl!(channel.label()), + Some(shown), + z, + true, + vec2(SLIDER_W, side), + &track, + ) { + (Some(z), ..) => pick = Some(field_pick(channel, z, x, y)), + (None, _, Some(v)) => pick = Some(field_pick(channel, (v / max as f64) as f32, x, y)), + _ => {} } }); } @@ -495,13 +529,18 @@ fn preview(app: &mut VectorcraftApp, d: &mut Dialog) { if unchanged || !selected { return; } - let _ = app.session.begin_interaction(if artboard { + let label = if artboard { "Artboard Options" } else if d.bool("stroke") { "Stroke Color" } else { "Fill Color" - }); + }; + // A failure to begin (typing that can't be kept) shows, and nothing previews. + if let Err(e) = app.begin_interaction(label) { + app.status(e); + return; + } if let Err(e) = app.session.preview(cmd, ¶ms) { app.status(e.to_string()); } @@ -724,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 9cb59853a6..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) { @@ -250,8 +250,14 @@ const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "des const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText"), ("Block", "block")]; /// Area Type Options › First Baseline. -const FIRST_BASELINE: form::Choices = - &[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")]; +const FIRST_BASELINE: form::Choices = &[ + ("Ascent", "ascent"), + ("Cap Height", "capHeight"), + ("x Height", "xHeight"), + ("Leading", "leading"), + ("Em Box Height", "emBoxHeight"), + ("Fixed", "fixed"), +]; /// Area Type Options › Align (vertical alignment of the lines in each row/column). const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")]; @@ -313,6 +319,35 @@ mod tests { assert_eq!(t.area.vertical_align, VerticalAlign::Center); } + /// Area Type Options › First Baseline offers Em Box Height: OK sets it with its Min, and the + /// dialog opens again with it chosen. + #[test] + fn area_type_options_dialog_sets_the_em_box_height_first_baseline() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 20, "text": "Hello", "area": {"width": 200, "height": 200}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + // The labels `i18n::tests::first_baseline_choices_are_in_complete_catalogs` checks. + let labels: Vec<&str> = choices("text.areaOptions", "firstBaseline").unwrap().iter().map(|(l, _)| *l).collect(); + assert_eq!(labels, ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"]); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "ascent"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("firstBaseline".into(), json!("emBoxHeight")); + fields.insert("firstBaselineMin".into(), json!(4.0)); + crate::dialogs::confirm(&mut app).unwrap(); + let NodeKind::Text(t) = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (vectorcraft_doc::FirstBaseline::EmBoxHeight, 4.0)); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "emBoxHeight"); + } + /// Area Type Options shows the gutter between rows beside the gutter, and OK sets a gutter /// between rows of its own. #[test] @@ -433,6 +468,47 @@ mod tests { assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); } + /// Object › Rasterize… opens this dialog with its options as parameter labels (#7991): in + /// French the heading, every field label and the resolution's unit ("ppp") are drawn in French. + #[test] + fn rasterize_dialog_is_drawn_in_the_ui_language() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Rasterize…").expect("listed"); + let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + crate::menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Rasterize"); + let keys: Vec = app.ui.dialog.as_ref().unwrap().fields.keys().filter(|k| !k.starts_with("__")).cloned().collect(); + assert_eq!(keys.len(), 6, "{keys:?}"); + assert_eq!(form::humanize("ppi"), "Resolution:"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let heading = heading_label(app.ui.dialog.as_ref().unwrap()); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(heading, "Pixelliser"); + let french = ["Ajouter autour de l’objet", "Lissage", "Arrière-plan", "Masque d’écrêtage", "Modèle colorimétrique", "Résolution", "ppp"]; + for s in french { + assert!(shown.contains(s), "{s} in {shown}"); + } + for s in ["Rasterize", "Add Around", "Anti Alias", "Background", "Clipping Mask", "Color Model", "Resolution", "Ppi", "ppi"] { + assert!(!shown.contains(s), "{s} left in English: {shown}"); + } + // Every language with complete menus heads the dialog as the menu item that opened it + // reads, and has a row for each label, the unit and the Color Model choices. + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + let menu = crate::i18n::tr(lang, &item.label); + assert_ne!(menu, item.label, "{}: menu item", lang.code()); + assert_eq!(heading_in(lang, "Rasterize"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code()); + let labels = keys.iter().map(|k| form::humanize(k).trim_end_matches(':').to_string()); + for label in labels.chain(["{n} ppi", "Grayscale", "Bitmap"].map(String::from)) { + assert!(crate::i18n::has(lang, &label), "{}: {label}", lang.code()); + } + } + } + /// Object › Path › Clean Up… opens this dialog headed "Clean Up", which most catalogs hold only /// as the menu label "Clean Up…" (#7991). In French the heading and every option are translated. #[test] @@ -530,6 +606,56 @@ mod tests { assert_eq!(cols(&app), 2, "one Undo takes the whole change back"); } + /// Grid Repeat Options labels its column fields Columns and Flip Columns, as the Rows and Flip + /// Rows fields beside them are spelled out. + #[test] + fn grid_repeat_options_spell_out_columns() { + let mut app = grid_options_app(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Rows:", "Columns:", "Flip Rows:", "Flip Columns:"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert!(!shown.contains("Cols"), "no Cols label: {shown}"); + } + + /// Object › Create Gradient Mesh… opens this dialog with the menu's rows, cols, appearance and + /// highlight. In French the heading and the four labels are translated, and "cols" is labeled + /// Columns (#7991). + #[test] + fn create_gradient_mesh_dialog_is_drawn_in_the_ui_language() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Create Gradient Mesh…").expect("listed"); + let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + crate::menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Create Gradient Mesh"); + assert_eq!(form::humanize("cols"), "Columns:"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let heading = heading_label(app.ui.dialog.as_ref().unwrap()); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(heading, "Créer un filet de dégradé"); + for s in ["Créer un filet de dégradé", "Lignes", "Colonnes", "Aspect"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + for s in ["Create Gradient Mesh", "Rows", "Cols", "Columns", "Appearance", "Highlight"] { + assert!(!shown.contains(s), "{s} left in English: {shown}"); + } + // Every language with complete menus heads the dialog as the menu item reads and has the + // four labels. + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + let menu = crate::i18n::tr(lang, &item.label); + assert_ne!(menu, item.label, "{}: menu item", lang.code()); + assert_eq!(heading_in(lang, "Create Gradient Mesh"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code()); + for key in ["rows", "cols", "appearance", "highlight"] { + let label = form::humanize(key); + assert!(crate::i18n::has(lang, label.trim_end_matches(':')), "{}: {label}", lang.code()); + } + } + } + /// Radial and Mirror Repeat Options have no Preview (their public pages list none): their /// fields apply on OK only, and the dialog takes no `preview`. #[test] 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 ac2798ec40..987fceeea4 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -41,7 +41,7 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, } else if !app.session.in_interaction() && d.fields.get(TRIED) != Some(¶ms) { // Waits for another interaction to end: trying inside it would replace its preview and // cancel it. A failure to begin leaves no interaction: the preview below then reports it. - let _ = app.session.begin_interaction(&d.str("__label")); + let _ = app.begin_interaction(&d.str("__label")); match app.session.preview(cmd, ¶ms) { Ok(_) => { d.fields.remove(form::REFUSED); @@ -255,9 +255,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("preview".into(), json!(pv)); if pv && (changed || pv_changed || !app.session.in_interaction()) { let label = d.str("__label"); - let _ = app.session.begin_interaction(&label); - let (cmd, p) = command(d); - let _ = app.session.preview(cmd, &p); + // A failure to begin (typing that can't be kept) shows, and nothing previews. + match app.begin_interaction(&label) { + Ok(()) => { + let (cmd, p) = command(d); + let _ = app.session.preview(cmd, &p); + } + Err(e) => app.status(e), + } } else if !pv && pv_changed { let _ = app.session.cancel_interaction(); } @@ -317,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 @@ -334,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()), @@ -391,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/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index fe0de205fc..39c2dc6c7c 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -1,4 +1,4 @@ -//! Effect → Effect Gallery: browse Photoshop-style raster filters by category, build a stack, and +//! Effect → Effect Gallery: browse raster filters by category, build a stack, and //! apply it as separate appearance effects in one undo step. //! //! Each filter has a thumbnail, and the dialog has its own preview, as the @@ -29,7 +29,7 @@ const PREVIEW_H: usize = 84; /// Dialog kind for the Effect Gallery. pub const KIND: &str = "effectGallery"; -/// Raster effect submenus in the gallery (the six Photoshop-style folders it holds). +/// Raster effect submenus in the gallery (the six raster filter folders it holds). const CATEGORIES: [(&str, &[&str]); 6] = [ ("Artistic", &["Effect", "Artistic"]), ("Brush Strokes", &["Effect", "Brush Strokes"]), @@ -313,11 +313,20 @@ fn stack_batch_params(stack: &[StackEntry]) -> Value { } /// Live canvas preview of the stack (`command.batch` would settle the dialog interaction each frame). +/// Typing in progress is kept as its own undo step first; only the gallery's own earlier preview is +/// canceled. fn preview_stack_on_canvas(app: &mut VectorcraftApp, stack: &[StackEntry]) { + if let Err(e) = app.keep_typing() { + app.status(e); + return; + } if app.session.in_interaction() { let _ = app.session.cancel_interaction(); } - let _ = app.session.begin_interaction("Effect Gallery"); + if let Err(e) = app.begin_interaction("Effect Gallery") { + app.status(e); + return; + } for (i, entry) in stack.iter().enumerate() { let params = Value::Object(entry.params.clone()); if app.run("effect.apply", json!({ "effect": entry.effect, "params": params })).is_err() { @@ -425,7 +434,7 @@ fn sample_drawing(w: usize, h: usize) -> Vec { out } -/// Run one Photoshop-style filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` +/// Run one raster filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` /// is not one of those filters or the buffer is the wrong size. fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, h: usize) { let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return }; @@ -766,6 +775,39 @@ mod tests { assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects.is_empty()); } + /// With Real-time Drawing off, typing in progress when the stack previews is kept as a step of + /// its own, not canceled with the gallery's earlier preview. + #[test] + fn stack_preview_keeps_typing_in_progress() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let id = vectorcraft_doc::NodeId(id); + let v = vectorcraft_engine::ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(" world", v).unwrap(); + let plain = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert_eq!(plain(&app), "Hello", "the typing waits"); + let steps = app.session.active().unwrap().history.undo.len(); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("stack".into(), json!([{ "effect": "artistic.cutout", "visible": true, "params": { "levels": 3 } }])); + frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Effect Gallery")); + assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own"); + assert_eq!(plain(&app), "Hello world"); + } + #[test] fn stack_ok_is_one_undo_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 8d34706df4..0eb1853065 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -6,14 +6,20 @@ //! Fields: `document.export` params (`format: eps`, `path?`, the artboard choice) and the EPS //! options of `document.exportEps`. OK remembers the options for next time and writes the file //! (asking where when there is no path); bad options keep the dialog open. +//! +//! Custom… beside the flattener preset opens Custom Transparency Flattener Options over the +//! dialog: its OK sets every flattener option as `flattener` (the preset then shows [Custom]) and +//! goes back to EPS Options; Cancel goes back with the options as they were. Choosing a preset +//! drops the custom options. use serde_json::{Map, Value, json}; -use vectorcraft_engine::cmd::{FlattenOptions, fileio}; +use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; use vectorcraft_eps::{Level, Overprint, Preview}; use super::DialogSpec; use super::document_setup::{LABEL, check, choice}; use crate::state::Dialog; +use crate::theme::Tokens; use crate::{VectorcraftApp, io, widgets}; pub(super) const KIND: &str = "epsOptions"; @@ -25,7 +31,18 @@ pub(super) const SPEC: DialogSpec = DialogSpec { ok: Some("Export"), min_width: 420.0, max_width: Some(460.0), - inputs: |_| &["path"], + inputs: |_| &["path", "flattener"], + ..DialogSpec::FORM +}; + +/// Custom Transparency Flattener Options, opened over EPS Options by Custom…. +pub(super) const CUSTOM_KIND: &str = "epsFlattenerOptions"; + +pub(super) const CUSTOM_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Custom Transparency Flattener Options").into(), + body: custom_body, + confirm: custom_confirm, + min_width: 420.0, ..DialogSpec::FORM }; @@ -61,11 +78,12 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } } - fields.insert("format".into(), json!("eps")); - // A built-in preset named by id (`medium`) shows as its name. - if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { - fields.insert("flattenerPreset".into(), json!(label)); + // A preset asked for without options of its own replaces the custom options used last. + if params.get("flattenerPreset").is_some() && params.get("flattener").is_none() { + fields.remove("flattener"); } + fields.insert("format".into(), json!("eps")); + builtin_label(&mut fields); app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); } @@ -90,8 +108,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let overprints: Vec<(&str, &str)> = Overprint::ALL.iter().map(|o| (o.id(), o.label())).collect(); choice(ui, d, "overprints", tl!("Overprints:"), &overprints); let presets = app.session.flattener_presets(); - let names: Vec<(&str, &str)> = presets.iter().map(|p| (p.name.as_str(), p.name.as_str())).collect(); - choice(ui, d, "flattenerPreset", tl!("Preset:"), &names); + let current = flattener(d, &app.session.prefs.flattener_presets).ok(); + let mut custom = false; + widgets::label_row(ui, tl!("Preset:"), LABEL, |ui| { + if let Some(p) = super::flatten::preset_dropdown(ui, "eps-flattener-preset", &presets, &d.str("flattenerPreset"), current.as_ref(), 180.0) { + d.fields.insert("flattenerPreset".into(), json!(p.name)); + d.fields.remove("flattener"); + } + custom = widgets::flat_button_fit(ui, tl!("Custom…"), 72.0).clicked(); + }); + if custom { + *d = over(d, &app.session.prefs.flattener_presets); + return false; + } ui.add_space(8.0); widgets::subheader(ui, tl!("Fonts")); // Type is written as glyph outlines, which need no fonts. @@ -122,6 +151,81 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// `ui.dialog.set` changed `field` of EPS Options `d`: a preset set there drops the Custom… +/// options, as choosing it in the dropdown does, and a built-in one named by id shows as its name. +pub(super) fn field_set(d: &mut Dialog, field: &str) { + if field == "flattenerPreset" { + d.fields.remove("flattener"); + builtin_label(&mut d.fields); + } +} + +/// A built-in preset named by id (`medium`) in `fields` shows as its name. +fn builtin_label(fields: &mut Map) { + if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { + fields.insert("flattenerPreset".into(), json!(label)); + } +} + +/// The flattener options EPS Options `d` exports with: its preset, with the Custom… options over it. +fn flattener(d: &Dialog, saved: &[FlattenerPreset]) -> Result { + FlattenOptions::for_export(d.fields.get("flattenerPreset").and_then(Value::as_str), d.fields.get("flattener"), saved) +} + +/// Custom Transparency Flattener Options over EPS Options `parent`, on the options it exports with +/// (the default preset's while those are not valid), without alpha: EPS has none. +pub(super) fn over(parent: &Dialog, saved: &[FlattenerPreset]) -> Dialog { + let mut o = flattener(parent, saved).unwrap_or_default(); + o.preserve_alpha = false; + let mut d = Dialog::new(CUSTOM_KIND, json!({})); + super::flatten::put_options(&mut d.fields, &o); + d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); + d +} + +/// The options Custom Transparency Flattener Options `d` holds. +fn custom_options(d: &Dialog) -> Result { + FlattenOptions::from_params_with(&Value::Object(d.fields.clone()), &[]) +} + +/// Whether the EPS Options under `d` keep overprints (Overprints: Preserve). +fn overprints_kept(d: &Dialog) -> bool { + super::parent(d).is_none_or(|p| Overprint::from_id(&p.str("overprints")) != Some(Overprint::Discard)) +} + +/// The flattener options; the two Preserve switches show what the export does and are set by the +/// format (no alpha) and by EPS Options' Overprints. +fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let current = custom_options(d); + // Values refused stay as entered, so that changing another option keeps them. The Preserve + // switches can't be set here, so the fields keep their own values of them. + let (mut o, unread) = super::flatten::shown_options(&d.fields, ¤t); + o.preserve_alpha = false; + o.preserve_overprints &= overprints_kept(d); + super::flatten::fields_editor(ui, "eps-flattener", &mut d.fields, &mut o, &unread, true); + if let Err(e) = ¤t { + ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); + } + ui.add_space(8.0); + super::form::caption(ui, tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); + false +} + +/// OK: EPS Options again, exporting with these options (a built-in preset under them, so that +/// deleting a saved preset leaves them whole); bad options keep the dialog open. +fn custom_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut o = custom_options(d)?; + o.preserve_alpha = false; + let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; + if FlattenOptions::preset(&parent.str("flattenerPreset")).is_none() { + let medium = FlattenOptions::preset_label(FlattenOptions::PRESETS[1]).unwrap_or_default(); + parent.fields.insert("flattenerPreset".into(), json!(medium)); + } + parent.fields.insert("flattener".into(), serde_json::to_value(&o).map_err(|e| e.to_string())?); + app.ui.dialog = Some(parent); + Ok(Value::Null) +} + /// Check the options, remember them, and write the file(s). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let params = fileio::eps::resolve(&super::form::params(d), &app.session.prefs.flattener_presets)?; diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index 383ea567df..cda98afada 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -1,7 +1,9 @@ //! Object → Expand: what to expand (Object: live shapes, type and effects; Fill: gradient and pattern fills; //! Stroke: strokes into filled outlines) and what gradient fills become (a gradient mesh, or a //! number of objects). Options the selection has nothing for are disabled. OK runs -//! `object.expand` as one undo step. +//! `object.expand` as one undo step and keeps its choices for the rest of the app's run: the dialog +//! opens on them, and Object › Expand… chosen with Alt (Option) expands with them at once +//! ([`expand_now`]). //! //! Fields: `object`, `fill`, `stroke`, `gradient` (`objects` | `mesh`), `steps` (1..1000), and //! `__object`, `__fill`, `__stroke` (that option has something to expand: `object.expand.info`), @@ -31,15 +33,51 @@ pub(crate) fn appearance_first() -> &'static str { tl!("Expand Appearance first (Object › Expand Appearance)") } -/// Open Expand for the selection, every option on (as `object.expand {}` does). A selection with -/// appearance attributes (effects, several fills or strokes…) refuses with [`appearance_first`]: -/// the menu item is dimmed for it. +/// Open Expand for the selection, on the choices OK last expanded with in this run of the app, or +/// every option on (as `object.expand {}` does) before that. A selection with appearance attributes +/// (effects, several fills or strokes…) refuses with [`appearance_first`]: the menu item is dimmed +/// for it. pub fn open(app: &mut VectorcraftApp) -> Result { + let fields = fields(app)?; + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(Value::Null) +} + +/// Object › Expand… chosen with Alt (Option): expand the selection at once, in one undo step, with +/// the choices OK last expanded with in this run of the app (the dialog's defaults before that), as +/// OK in the dialog opened on them would. When none of those choices has something to expand in the +/// selection, the dialog opens on them instead, and nothing changes. A selection with appearance +/// attributes refuses with [`appearance_first`], as [`open`] does. +pub fn expand_now(app: &mut VectorcraftApp) -> Result { + let d = Dialog::new(KIND, fields(app)?); + if !OPTIONS.iter().any(|(key, _)| d.bool(key) && option_enabled(&d, key)) { + app.ui.dialog = Some(d); + return Ok(Value::Null); + } + app.run(CMD, params(&d)) +} + +/// The choices OK last expanded with (`app.ui.expand_options`), when each one holds a value the +/// dialog shows: a switch for Object, Fill and Stroke, `objects` or `mesh`, and 1 to 1000 steps. +fn remembered(app: &VectorcraftApp) -> Option<&Value> { + let o = &app.ui.expand_options; + let switches = OPTIONS.iter().all(|(key, _)| o[key].is_boolean()); + let gradient = matches!(o["gradient"].as_str(), Some("objects" | "mesh")); + let steps = o["steps"].as_f64().is_some_and(|n| (1.0..=MAX_STEPS as f64).contains(&n.round())); + (switches && gradient && steps).then_some(o) +} + +/// The dialog's fields for the selection: the remembered choices (or the defaults) and what each +/// option has to expand. +fn fields(app: &mut VectorcraftApp) -> Result { let info = app.session.execute("object.expand.info", &json!({})).map_err(|e| e.to_string())?; if info["appearance"] == json!(true) { return Err(appearance_first().into()); } - let mut fields = json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}); + let mut fields = match remembered(app) { + Some(o) => json!({"object": o["object"], "fill": o["fill"], "stroke": o["stroke"], "gradient": o["gradient"], "steps": o["steps"]}), + None => json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}), + }; for (key, _) in OPTIONS { fields[format!("__{key}")] = info[key].clone(); } @@ -47,8 +85,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { for key in ["fill", "stroke", "gradient"] { fields[format!("__{key}_symbol")] = json!(info["symbolArt"][key] == json!(true)); } - app.ui.dialog = Some(Dialog::new(KIND, fields)); - Ok(Value::Null) + Ok(fields) } fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { @@ -112,8 +149,12 @@ fn params(d: &Dialog) -> Value { }) } +/// OK: expand, and keep the choices once the expansion succeeded. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - run_and_close(app, CMD, params(d)) + let choices = params(d); + let r = run_and_close(app, CMD, choices.clone())?; + app.ui.expand_options = choices; + Ok(r) } #[cfg(test)] @@ -253,4 +294,140 @@ mod tests { app.run("select.none", json!({})).unwrap(); assert!(!crate::menus::enabled(&app, "ui.expandDialog")); } + + /// A rectangle with a linear gradient fill and no stroke is selected. + fn gradient_rectangle(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + app.run("paint.setFill", json!({"gradient": {"kind": "linear"}})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + } + + /// Object › Expand… from the in-window menu, with Alt held or not. + fn choose_expand(app: &mut VectorcraftApp, alt: bool) { + let entries = crate::menus::menu_entries(app); + let e = entries.iter().find(|e| e.path == ["Object"] && e.label == "Expand…").expect("Object › Expand…"); + assert!(e.enabled, "Expand… is available"); + let target = crate::menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); + let held = if alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE }; + let (cmd, p) = crate::menus::with_held_keys(target, held); + crate::menus::invoke(app, &cmd, p); + } + + /// Whether the selected object is a clip group holding a gradient mesh (Expand Gradient To › + /// Gradient Mesh) rather than solid objects. + fn expanded_to_a_mesh(app: &VectorcraftApp) -> bool { + let st = app.session.doc().unwrap(); + let g = st.doc.node(st.selection.objects[0]).unwrap(); + let NodeKind::Group { children, clip: true } = &g.kind else { panic!("a clip group: {:?}", g.kind) }; + children.iter().any(|c| matches!(c.kind, NodeKind::Mesh(_))) + } + + #[test] + fn the_dialog_opens_on_the_choices_ok_last_expanded_with() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + choose_expand(&mut app, false); + let d = app.ui.dialog.as_mut().expect("the Expand dialog"); + d.fields.insert("gradient".into(), json!("mesh")); + d.fields.insert("steps".into(), json!(12)); + d.fields.insert("stroke".into(), json!(false)); + super::super::confirm(&mut app).unwrap(); + assert!(expanded_to_a_mesh(&app)); + app.run("edit.undo", json!({})).unwrap(); + let kept = json!({"object": true, "fill": true, "stroke": false, "gradient": "mesh", "steps": 12.0}); + choose_expand(&mut app, false); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept, "it opens on the choices OK expanded with"); + // Cancel leaves them as they were. + app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("objects")); + super::super::cancel(&mut app); + assert_eq!(app.ui.expand_options, kept); + // So does an OK that fails, and nothing changes. + choose_expand(&mut app, false); + app.ui.dialog.as_mut().unwrap().fields.insert("steps".into(), json!(5000)); + let before = app.session.doc().unwrap().doc.clone(); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.ui.expand_options, kept); + choose_expand(&mut app, false); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept); + } + + #[test] + fn alt_expands_at_once_with_the_choices_ok_last_expanded_with() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + choose_expand(&mut app, false); + app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("mesh")); + super::super::confirm(&mut app).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!(expanded_to_a_mesh(&app), "the kept Gradient Mesh choice"); + } + + #[test] + fn alt_before_any_ok_expands_with_the_defaults() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert!(!expanded_to_a_mesh(&app), "the gradient becomes objects, the default"); + assert!(app.ui.expand_options.is_null(), "Alt keeps no choices of its own"); + } + + #[test] + fn alt_opens_the_dialog_when_the_kept_choices_expand_nothing_in_the_selection() { + 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": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + // Fill alone was kept, and a plain rectangle has no gradient or pattern fill. + app.ui.expand_options = json!({"object": false, "fill": true, "stroke": false, "gradient": "objects", "steps": 255.0}); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + let d = app.ui.dialog.as_ref().expect("the Expand dialog"); + assert_eq!(params(d), app.ui.expand_options, "it opens on the kept choices"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing recorded"); + assert_eq!(app.session.doc().unwrap().doc, before); + } + + #[test] + fn alt_refuses_a_selection_with_appearance_attributes_and_a_bad_immediate() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + zig_zag_line(&mut app); + let before = app.session.doc().unwrap().doc.clone(); + assert_eq!(app.run("ui.expandDialog", json!({"immediate": true})).unwrap_err(), appearance_first()); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc, before, "the line is left as it was"); + app.run("effect.expandAppearance", json!({})).unwrap(); + assert!(app.run("ui.expandDialog", json!({"immediate": "yes"})).is_err()); + assert!(app.ui.dialog.is_none()); + app.run("ui.expandDialog", json!({"immediate": false})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + } + + #[test] + fn kept_choices_with_a_value_the_dialog_does_not_show_are_left_out() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + for bad in [ + json!({"object": "yes", "fill": true, "stroke": true, "gradient": "mesh", "steps": 12}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "strips", "steps": 12}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh", "steps": 0}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh"}), + ] { + app.ui.expand_options = bad; + app.run("ui.expandDialog", json!({})).unwrap(); + assert_eq!( + params(app.ui.dialog.as_ref().unwrap()), + json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0}) + ); + app.ui.dialog = None; + } + } } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index cd18d6b153..60701aae13 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -2,7 +2,7 @@ //! artboard, after a central file of the whole document for EPS with two or more when art shows, //! or one page each in a PDF); without artboards the export covers the visible art. OK //! picks the file, then the format's options dialog follows (PNG/JPEG/WebP/PNG-8/GIF Options, SVG -//! Options, Text Export Options, DXF Options, EPS Options, and Save PDF), +//! Options, Text Export Options, DXF Options, EPS Options, HP-GL Options, and Save PDF), //! else the file is written. DWG is listed, greyed out, with what to use instead. The formats of //! installed exporter plug-ins come after the built-in ones: they write the whole document (from //! Export Selection, the selection), and one with parameters asks for them before writing @@ -14,7 +14,7 @@ use std::sync::LazyLock; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; -use super::{DialogSpec, dxf_options, eps_options, form, plugin, png_options, save_pdf, svg_options, text_export}; +use super::{DialogSpec, dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, io, widgets}; @@ -234,7 +234,7 @@ fn options_or_write( } } let plugin = plugin.filter(|p| !p.manifest().params.is_empty()); - let dialog = plugin.is_none() && (f.raster || matches!(f.id, "dxf" | "eps")); + let dialog = plugin.is_none() && (f.raster || matches!(f.id, "dxf" | "eps" | "hpgl")); if selection { // An options dialog keeps the mark as a field of its own, which OK hands on. params[if dialog { SELECTION_FIELD } else { io::EXPORT_SELECTION }] = json!(true); @@ -255,6 +255,10 @@ fn options_or_write( eps_options::open(app, ¶ms); return Ok(Value::Null); } + if f.id == "hpgl" { + hpgl_options::open(app, ¶ms); + return Ok(Value::Null); + } return io::export(app, Some(f.id), Some(path), ¶ms); } }; diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 026f477a0e..298e6d2c45 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -1,4 +1,4 @@ -//! File → Export → Export for Screens, laid out as Illustrator's: on the left the Artboards and +//! File → Export → Export for Screens: on the left the Artboards and //! Assets tabs (thumbnails with checkboxes, in a grid or a list), Clear Selection and the prefix; //! on the right Select (All, a range or Full Document, Include Bleed, Include Artboard Fill), the destination (folder //! picker, Open Location after Export, Create Sub-folders by scale or by format; the web downloads @@ -721,7 +721,7 @@ fn tiles( ui.painter().galley(label_pos, galley, t.text); false }; - // The checkbox sits on the thumbnail's lower left corner, as Illustrator's. + // The checkbox sits on the thumbnail's lower left corner. let bx = egui::Rect::from_min_size(egui::pos2(pic.left() + 4.0, pic.bottom() - 18.0), egui::vec2(14.0, 14.0)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bx)); if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() || caption_clicked { 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/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 0c5bc7dbee..a22631c8e2 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -48,6 +48,53 @@ pub(crate) fn put_options(fields: &mut Map, o: &FlattenOptions) { } } +/// The options `fields` hold over `base` as they were entered, values out of range included, for +/// the editor to show while [`FlattenOptions::from_params_with`] refuses them, and the keys of the +/// values of the wrong type, which take `base`'s value here and show blank in the editor. +pub(crate) fn entered_options(fields: &Map, base: &FlattenOptions) -> (FlattenOptions, Vec) { + let Ok(Value::Object(mut v)) = serde_json::to_value(base) else { return (base.clone(), Vec::new()) }; + let mut unread = Vec::new(); + for (k, val) in fields { + let Some(slot) = v.get_mut(k) else { continue }; + let old = std::mem::replace(slot, val.clone()); + if serde_json::from_value::(Value::Object(v.clone())).is_err() { + v.insert(k.clone(), old); + unread.push(k.clone()); + } + } + (serde_json::from_value(Value::Object(v)).unwrap_or_else(|_| base.clone()), unread) +} + +/// The options a dialog's `fields` hold, for [`fields_editor`]: `current` when they are valid, else +/// the values entered over the default preset's, with the keys of the values of the wrong type. +pub(crate) fn shown_options(fields: &Map, current: &Result) -> (FlattenOptions, Vec) { + match current { + Ok(o) => (o.clone(), Vec::new()), + Err(_) => entered_options(fields, &FlattenOptions::default()), + } +} + +/// [`options_editor`] on the option fields of a dialog: `o` and `unread` from [`shown_options`]. +/// Each option whose control was set is written into `fields`, also when it equals the value shown, +/// so that it replaces a value of the wrong type; the other fields stay as they were entered. With +/// `fixed_preserve`, the two Preserve switches show but can't be changed. +pub(crate) fn fields_editor( + ui: &mut egui::Ui, + id: &str, + fields: &mut Map, + o: &mut FlattenOptions, + unread: &[String], + fixed_preserve: bool, +) { + let set = editor(ui, id, o, true, fixed_preserve, unread); + let Ok(Value::Object(m)) = serde_json::to_value(&*o) else { return }; + for k in set { + if let Some(v) = m.get(k) { + fields.insert(k.into(), v.clone()); + } + } +} + /// The options the fields hold (a `preset` not loaded yet: its own). fn options(d: &Dialog, saved: &[FlattenerPreset]) -> Result { if d.str("preset") != d.str(APPLIED) { @@ -101,10 +148,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { save_row(app, ui, d); } ui.add_space(10.0); - let mut o = current.clone().unwrap_or_default(); - if options_editor(ui, "flatten-dialog", &mut o, true) { - put_options(&mut d.fields, &o); - } + // Values refused stay as entered, so that changing another option keeps them. + let (mut o, unread) = shown_options(&d.fields, ¤t); + fields_editor(ui, "flatten-dialog", &mut d.fields, &mut o, &unread, false); if let Err(e) = ¤t { ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); } @@ -180,8 +226,19 @@ const FIELD: f32 = 56.0; /// panel edit them: the raster/vector balance, both resolutions and the six switches. Returns true /// when one changed. pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool) -> bool { - let t = Tokens::get(ui.ctx()); let before = o.clone(); + editor(ui, id, o, enabled, false, &[]); + *o != before +} + +/// The option controls, with the value fields of the options named in `unread` blank. With +/// `fixed_preserve`, Preserve Alpha Transparency and Preserve Overprints and Spot Colors show but +/// can't be changed (the file format or another control sets them). Returns the keys of the +/// options whose controls were set, also to the value they showed. +fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fixed_preserve: bool, unread: &[String]) -> Vec<&'static str> { + let t = Tokens::get(ui.ctx()); + let mut set = Vec::new(); + let field_value = |key: &str, v: f64| (!unread.iter().any(|k| k == key)).then_some(v); let dim = |ui: &mut egui::Ui, s: &str| { ui.label(egui::RichText::new(tl!(s)).color(t.text_dim).size(11.5)); }; @@ -203,44 +260,51 @@ pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions ); if let Some(b) = x.map(|x| (x as f64 * 100.0).round()).or(keyed) { o.balance = b; + set.push("balance"); } dim(ui, tl!("Vectors")); + let value = field_value("balance", o.balance); if let Some(v) = - widgets::range_field_named(ui, (id, "balance"), Some(tl!("Raster/Vector Balance:")), o.balance, 0.0..=100.0, "", 0, FIELD - 12.0) + widgets::range_field_named(ui, (id, "balance"), Some(tl!("Raster/Vector Balance:")), value, 0.0..=100.0, "", 0, FIELD - 12.0) { o.balance = v; + set.push("balance"); } }); ui.add_space(4.0); egui::Grid::new((id, "resolutions")).num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| { - for (label, key) in [(tl!("Line Art and Text Resolution:"), 0), (tl!("Gradient and Mesh Resolution:"), 1)] { + for (label, key, name) in + [(tl!("Line Art and Text Resolution:"), 0, "lineArtPpi"), (tl!("Gradient and Mesh Resolution:"), 1, "gradientPpi")] + { widgets::dim_label(ui, label); ui.horizontal(|ui| { let v = if key == 0 { &mut o.line_art_ppi } else { &mut o.gradient_ppi }; - if let Some(n) = widgets::range_field_named(ui, (id, key), Some(label), *v, 1.0..=2400.0, "", 0, FIELD) { + if let Some(n) = widgets::range_field_named(ui, (id, key), Some(label), field_value(name, *v), 1.0..=2400.0, "", 0, FIELD) { *v = n; + set.push(name); } - dim(ui, "ppi"); + dim(ui, super::ppi_suffix().trim()); }); ui.end_row(); } }); ui.add_space(4.0); - let switches: [(&str, &mut bool); 6] = [ - (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines), - (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines), - (tl!("Clip Complex Regions"), &mut o.clip_complex_regions), - (tl!("Anti-alias Rasters"), &mut o.anti_alias), - (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha), - (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints), + let switches: [(&str, &mut bool, bool, &'static str); 6] = [ + (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines, false, "textToOutlines"), + (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines, false, "strokesToOutlines"), + (tl!("Clip Complex Regions"), &mut o.clip_complex_regions, false, "clipComplexRegions"), + (tl!("Anti-alias Rasters"), &mut o.anti_alias, false, "antiAlias"), + (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha, fixed_preserve, "preserveAlpha"), + (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints, fixed_preserve, "preserveOverprints"), ]; - for (label, v) in switches { - if widgets::check(ui, label, *v, enabled) { + for (label, v, fixed, key) in switches { + if widgets::check(ui, label, *v, enabled && !fixed) { *v = !*v; + set.push(key); } } }); - *o != before + set } #[cfg(test)] @@ -394,4 +458,42 @@ mod tests { assert!(super::super::confirm(&mut app).unwrap_err().contains("resolutions")); assert!(app.ui.dialog.is_some()); } + + /// Changing a switch beside a value out of range keeps the values entered. + #[test] + fn a_switch_changed_beside_a_bad_value_keeps_the_values_entered() { + let mut app = scene(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("balance".into(), json!(20)); + d.fields.insert("gradientPpi".into(), json!(9000)); + d.fields.insert("lineArtPpi".into(), json!("many")); + let mut f = super::super::tests_eps::Frames::new(); + let (_, at) = f.control(&mut app, "Convert All Text to Outlines", egui::accesskit::Role::CheckBox); + let before = app.ui.dialog.as_ref().unwrap().bool("textToOutlines"); + f.click(&mut app, at); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.bool("textToOutlines"), !before, "the switch changes"); + assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (20.0, 9000.0), "the other values stay as entered"); + assert_eq!(d.fields["lineArtPpi"], json!("many"), "a value of the wrong type stays to be refused"); + assert!(super::super::confirm(&mut app).is_err()); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lineArtPpi".into(), json!(300)); + assert!(super::super::confirm(&mut app).unwrap_err().contains("resolutions")); + } + + /// A value of the wrong type shows blank, and typing the default preset's value into its + /// field replaces it, so OK flattens. + #[test] + fn the_default_value_typed_over_a_value_of_the_wrong_type_replaces_it() { + let mut app = scene(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("lineArtPpi".into(), json!("many")); + let default = FlattenOptions::default().line_art_ppi; + let mut f = super::super::tests_eps::Frames::new(); + f.type_into(&mut app, "Line Art and Text Resolution:", &default.to_string()); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["lineArtPpi"], json!(default)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && !transparent_left(&app)); + } } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index d386c1f028..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) { @@ -503,7 +511,9 @@ pub(super) fn param_fields( } } Value::Number(n) => { - if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), "", 3, 140.0) { + // A resolution (Object › Rasterize's `ppi`) shows its unit in the UI language. + let suffix = if k == "ppi" { crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) } else { String::new() }; + if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), &suffix, 3, 140.0) { d.fields.insert(k.clone(), typed_number(x)); changed = true; } @@ -778,6 +788,12 @@ pub(crate) fn unit_suffix(unit: &str) -> String { if unit.is_empty() || unit.starts_with(['°', '%', '′', '″']) { unit.to_string() } else { format!(" {unit}") } } +/// What a resolution field shows after its value in the interface language: the `{n} ppi` row +/// without its number (" ppi", French " ppp"). +pub(crate) fn ppi_suffix() -> String { + crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) +} + /// A number of a list as [`value_field`] shows it: at most 4 decimals, without trailing zeros. fn number_text(x: f64) -> String { let s = format!("{x:.4}"); @@ -798,6 +814,7 @@ pub(crate) fn humanize(k: &str) -> String { } } match s.as_str() { + "Ppi" => "Resolution:".into(), "Dx" => "Horizontal".into(), "Dy" => "Vertical".into(), "Sx" => "Horizontal %".into(), @@ -828,15 +845,23 @@ pub(crate) fn humanize(k: &str) -> String { "Create" => "Create New Fields by:".into(), "Height Width" => "Height/Width:".into(), "Traps With Process Color" => "Traps with Process Color:".into(), + "Cols" => "Columns:".into(), + "Flip Cols" => "Flip Columns:".into(), _ => format!("{s}:"), } } -/// [`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(), } } @@ -1040,7 +1065,12 @@ fn preview_or_rollback(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: & pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) -> Option { let mut result = None; if d.fields.get(PREVIEWED) != Some(¶ms) || !app.session.in_interaction() { - let _ = app.session.begin_interaction(label); + // A failure to begin (typing that can't be kept) shows, and nothing previews on the + // interaction still in progress. + if let Err(e) = app.begin_interaction(label) { + app.status(e); + return None; + } match app.session.preview(cmd, ¶ms) { Ok(r) => { d.fields.remove(REFUSED); @@ -1154,6 +1184,27 @@ mod plugin_field_tests { assert_eq!([shown("mm"), shown("°"), shown("%"), shown("1/min"), shown("µm")], ["5 mm", "5°", "5%", "5 1/min", "5 µm"]); } + /// A resolution field's unit is the `{n} ppi` row without its number. + #[test] + fn the_ppi_unit_is_translated() { + assert_eq!(ppi_suffix(), " ppi"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let fr = ppi_suffix(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(fr, " ppp"); + } + + /// [`ppi_suffix`] drops the number from the `{n} ppi` row, so every catalog writes the number + /// first and then a space before the unit. + #[test] + fn every_catalog_writes_the_ppi_unit_after_the_number() { + for lang in crate::i18n::Lang::all() { + let row = crate::i18n::tr(lang, "{n} ppi"); + let unit = row.strip_prefix("{n}").unwrap_or_default(); + assert!(unit.starts_with(char::is_whitespace) && !unit.trim().is_empty(), "{}: {row:?}", lang.code()); + } + } + #[test] fn number_lists_read_as_typed_within_their_limits() { let spec = ParamSpec::NumberList { min: 0.0, max: 360.0, default: vec![45.0], min_items: 1, max_items: 3 }; @@ -1167,6 +1218,98 @@ mod plugin_field_tests { } } +#[cfg(test)] +mod settled_typing_tests { + use super::*; + use vectorcraft_engine::{Session, ViewInfo}; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + /// An app with Real-time Drawing off and " world" typed after "Hello", not yet applied → the + /// type's id. + fn typing(app: &mut crate::VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(" world", v).unwrap(); + id + } + + fn plain(app: &crate::VectorcraftApp, id: u64) -> String { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + } + + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts + /// from it; the status bar shows the warning of the typing's preview that keeping it applied. + #[test] + fn a_dialog_preview_keeps_the_typing_and_shows_its_warning() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + assert_eq!(plain(&app, id), "Hello", "the typing waits"); + let steps = app.session.active().unwrap().history.undo.len(); + let mut d = Dialog::new("test", json!({})); + assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some()); + assert_eq!(plain(&app, id), "Hello world"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own"); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Fill Color")); + + // The typing's deferred preview warns that type is skipped (as Bloat does with type selected). + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 300, "y": 200, "text": "Hi"})).unwrap(); + app.run("select.set", json!({"ids": [rect["id"], text["id"]]})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + app.session.begin_interaction("Typing").unwrap(); + let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0}); + app.session.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p)); + app.ui.status.clear(); + let mut d = Dialog::new("test", json!({})); + assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some()); + assert!(app.ui.status.contains("type"), "{:?}", app.ui.status); + } + + /// The font menus end the typing session before their preview: the typing Real-time Drawing + /// off left unapplied is kept as a step of its own. + #[test] + fn ending_typing_for_the_font_menus_keeps_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + let steps = app.session.active().unwrap().history.undo.len(); + crate::panels::character::end_typing(&mut app); + assert_eq!(plain(&app, id), "Hello world"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1); + assert!(st.interaction.is_none()); + assert_ne!(app.session.tool_options().get("typing").and_then(Value::as_bool), Some(true), "the typing session is over"); + } + + /// A Character panel change keeps the typing first and acts on the characters the Type tool + /// selected in the typed text, not on a selection cut short to the text before the typing. + #[test] + fn a_character_change_acts_on_characters_selected_in_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + app.session.set_tool_option("select", &json!({"start": 6, "end": 11})); + crate::panels::character::range_style(&mut app, json!({"underline": true})); + assert_eq!(plain(&app, id), "Hello world"); + let vectorcraft_doc::NodeKind::Text(t) = &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { + panic!("not text") + }; + let underlined: String = t.runs.iter().filter(|r| r.style.underline).map(|r| r.text.as_str()).collect(); + assert_eq!(underlined, "world"); + } +} + #[cfg(test)] mod typed_number_tests { use super::*; 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_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 90cc7d9f55..ab46dbd82c 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -28,14 +28,13 @@ use crate::{VectorcraftApp, widgets}; pub const KIND: &str = "graphData"; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its -/// series; the least it shows; a cell's longest text. +/// series; the least it shows. const MAX_ROWS: usize = MAX_GRAPH_CATEGORIES + 1; const MAX_COLS: usize = MAX_GRAPH_SERIES + 1; const MIN_ROWS: usize = 8; const MIN_COLS: usize = 6; -const MAX_CELL: usize = 256; /// The largest file Import Data reads, 1 MB (1,048,576 bytes), the same as Import Data Sets'. -const MAX_IMPORT_BYTES: usize = 1 << 20; +const MAX_IMPORT_BYTES: usize = vectorcraft_engine::cmd::MAX_GRAPH_DATA_FILE; /// The Cell Style limits (Adjust column width and decimal digits). const MAX_DECIMALS: u64 = 10; const MAX_WIDTH: u64 = 20; @@ -105,75 +104,25 @@ pub(crate) fn grid_from_data(v: &Value) -> Grid { grid } -/// The sheet as `graph.setData` takes it: series labels, category labels (none when all are blank) -/// and the values (a blank cell, or text that isn't a number, has none), without the empty rows and -/// columns past the data. +/// The sheet as `graph.setData` takes it ([`vectorcraft_engine::cmd::graph_data_from_grid`]), +/// which Import Data Sets' `%` columns also use. pub(crate) fn data_from_grid(grid: &Grid) -> Value { - let filled = |s: &String| !s.trim().is_empty(); - // At most a graph's rows and columns, as a file gives (`grid_from_text`): a grid sent by - // automation is any size, and the values are their product. - let grid = &grid[..grid.len().min(MAX_ROWS)]; - let rows = grid.iter().rposition(|r| r.iter().take(MAX_COLS).any(filled)).map_or(1, |i| i + 1).max(1); - let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(MAX_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); - let label = |s: &str| { - let s = s.trim(); - // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. - s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() - }; - // Series labels up to the last one given (none when all are blank). - let mut series: Vec = (1..cols).map(|c| label(&cell(grid, 0, c))).collect(); - while series.last().is_some_and(String::is_empty) { - series.pop(); - } - let mut categories: Vec = (1..rows).map(|r| label(&cell(grid, r, 0))).collect(); - if categories.iter().all(String::is_empty) { - categories.clear(); - } - let values: Vec> = (1..rows) - .map(|r| { - (1..cols) - .map(|c| { - let t = cell(grid, r, c); - t.trim().parse::().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) - }) - .collect() - }) - .collect(); - json!({ "series": series, "categories": categories, "rows": values }) + vectorcraft_engine::cmd::graph_data_from_grid(grid) } -/// Text from a file or the clipboard as cells: tab-separated when any line holds a tab, else -/// comma-separated (decided once, so a label with a comma in a tab-separated file stays whole), at -/// most a graph's rows and columns. +/// Text from a file or the clipboard as cells ([`vectorcraft_engine::cmd::graph_grid_from_text`]). pub(crate) fn grid_from_text(text: &str) -> Grid { - let sep = if text.contains('\t') { '\t' } else { ',' }; - text.lines().take(MAX_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(MAX_COLS).map(|c| clean(c.trim())).collect()).collect() + vectorcraft_engine::cmd::graph_grid_from_text(text) } -/// A text file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode Text"), -/// else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives them a -/// byte order ([`vectorcraft_engine::cmd::utf16_order_without_mark`]), else UTF-8 with or without -/// one. UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an -/// unpaired surrogate reads as U+FFFD. +/// A text file's bytes as text ([`vectorcraft_engine::cmd::graph_data_text`]). pub(crate) fn decode(bytes: &[u8]) -> String { - let utf16 = |rest: &[u8], le: bool| { - let units: Vec = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); - String::from_utf16_lossy(&units) - }; - match bytes { - [0xFF, 0xFE, rest @ ..] => utf16(rest, true), - [0xFE, 0xFF, rest @ ..] => utf16(rest, false), - [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), - _ => match bytes.contains(&0).then(|| vectorcraft_engine::cmd::utf16_order_without_mark(bytes)).flatten() { - Some(le) => utf16(bytes, le), - None => String::from_utf8_lossy(bytes).into_owned(), - }, - } + vectorcraft_engine::cmd::graph_data_text(bytes) } -/// A cell's text: one line (tabs and line breaks become spaces), at most MAX_CELL characters. +/// A cell's text ([`vectorcraft_engine::cmd::graph_cell_text`]). fn clean(s: &str) -> String { - s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(MAX_CELL).collect() + vectorcraft_engine::cmd::graph_cell_text(s) } fn cell(grid: &[Vec], r: usize, c: usize) -> String { 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/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs new file mode 100644 index 0000000000..5bbc6b3e6b --- /dev/null +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -0,0 +1,265 @@ +//! HP-GL Options (Export As → HP-GL): the language version, the curve tolerance, where the plot's +//! origin lies, the pens (one per color the art draws in, or a pen table of colors), and the order +//! the paths are drawn in (the nearest path next, inner paths first). +//! +//! Fields: `document.export` params (`format: hpgl`, `path?`, the artboard choice) and the HP-GL +//! options (`hpglVersion`, `curveTolerance`, `origin`, `pens`, `sortPaths`, `insideFirst`). OK +//! remembers the options for next time and writes the file (asking where when there is no path); +//! an option or artboard choice the export refuses, or a save panel shown in line that is canceled, +//! keeps the dialog open. A canceled save panel keeps the options remembered before. Opened by Export +//! Selection, it checks and writes the selection alone. A typed Curve Tolerance is kept within 0.01 +//! to 10 points. + +use serde_json::{Map, Value, json}; +use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; +use vectorcraft_cad::hpgl::{Origin, Version}; +use vectorcraft_engine::cmd::fileio; + +use super::DialogSpec; +use super::document_setup::{LABEL, check, choice}; +use crate::state::Dialog; +use crate::{VectorcraftApp, io, widgets}; + +pub(super) const KIND: &str = "hpglOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("HP-GL Options").into(), + body, + confirm, + ok: Some("Export"), + min_width: 420.0, + max_width: Some(460.0), + inputs: |_| &["path"], + ..DialogSpec::FORM +}; + +/// Fields that are not remembered between exports (they belong to one export). +const PER_EXPORT: [&str; 8] = ["format", "path", "useArtboards", "range", "artboard", "artboards", "selectedOnly", io::EXPORT_SELECTION]; + +/// The pen table set aside while One Pen per Color is chosen, so Pen Table shows it again. +const SET_ASIDE: &str = "__pens"; + +/// Why Pen Table could not start from the art's pens, shown under the Pens row. +const PEN_ERROR: &str = "__penError"; + +/// The Origin menu's names, in [`Origin::ALL`] order. +pub(crate) const ORIGIN_NAMES: [&str; 2] = ["Bottom Left", "Center"]; + +/// The options a first HP-GL Options dialog starts from (the export's defaults). +fn defaults() -> Map { + let mut m = Map::new(); + for (k, v) in [ + ("hpglVersion", json!(Version::default().id())), + ("curveTolerance", json!(DEFAULT_TOLERANCE)), + ("origin", json!(Origin::default().id())), + ("pens", Value::Null), + ("sortPaths", json!(false)), + ("insideFirst", json!(false)), + ] { + m.insert(k.into(), v); + } + m +} + +/// Open HP-GL Options for an export whose params (path, artboard choice, any HP-GL option) are +/// `params`, over the options used last. +pub fn open(app: &mut VectorcraftApp, params: &Value) { + let mut fields = defaults(); + for given in [&app.ui.hpgl_options, params] { + if let Some(o) = given.as_object() { + fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); + } + } + fields.insert("format".into(), json!("hpgl")); + app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let versions: Vec<(&str, &str)> = Version::ALL.iter().map(|v| (v.id(), v.label())).collect(); + choice(ui, d, "hpglVersion", tl!("Version:"), &versions); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Curve Tolerance:"), LABEL, |ui| { + let x = d.f64("curveTolerance", DEFAULT_TOLERANCE); + if let Some(v) = widgets::plain_field(ui, "hpgl-tolerance", x, " pt", 2, 80.0) { + let (lo, hi) = (*TOLERANCE_RANGE.start(), *TOLERANCE_RANGE.end()); + d.fields.insert("curveTolerance".into(), json!(v.clamp(lo, hi))); + } + }); + ui.add_space(4.0); + let origins: Vec<(&str, &str)> = Origin::ALL.iter().map(|o| o.id()).zip(ORIGIN_NAMES).collect(); + choice(ui, d, "origin", tl!("Origin:"), &origins); + ui.add_space(10.0); + pens(app, ui, d); + ui.add_space(8.0); + check(ui, d, "sortPaths", tl!("Draw the Nearest Path Next")); + check(ui, d, "insideFirst", tl!("Draw Inner Paths First")); + false +} + +/// Pens: One Pen per Color (`pens` null) or Pen Table (`pens` the colors, pen 1's first), with a +/// row per pen (its number, color and a Remove button) and Add. +fn pens(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + let table = d.fields.get("pens").is_some_and(Value::is_array); + widgets::label_row(ui, tl!("Pens:"), LABEL, |ui| { + if widgets::radio(ui, tl!("One Pen per Color"), !table, true) { + let _ = set_pen_table(d, false, || Ok(Vec::new())); + d.fields.remove(PEN_ERROR); + } + ui.add_space(12.0); + if widgets::radio(ui, tl!("Pen Table"), table, true) { + let shown = d.clone(); + match set_pen_table(d, true, || automatic_pens(app, &shown)) { + Ok(()) => d.fields.remove(PEN_ERROR), + Err(e) => d.fields.insert(PEN_ERROR.into(), json!(e)), + }; + } + }); + if let Some(e) = d.fields.get(PEN_ERROR).and_then(Value::as_str) { + let t = crate::theme::Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), e)).color(t.error)); + } + // The table as the radio buttons left it, so a row edit committed this frame can't undo a switch. + // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. + let Some(mut list) = d.fields.get("pens").and_then(Value::as_array).filter(|a| a.len() <= MAX_PENS).cloned() else { return }; + let t = crate::theme::Tokens::get(ui.ctx()); + let n = list.len(); + let (mut changed, mut remove) = (false, None); + egui::ScrollArea::vertical().id_salt("hpgl-pens").max_height(180.0).auto_shrink([false, true]).show(ui, |ui| { + for (i, v) in list.iter_mut().enumerate() { + ui.horizontal(|ui| { + ui.add_space(LABEL + 8.0); + ui.add_sized([28.0, 18.0], egui::Label::new(egui::RichText::new((i + 1).to_string()).color(t.text))); + let hex = v.as_str().and_then(|s| s.strip_prefix('#')).unwrap_or_default().to_string(); + let (rect, _) = ui.allocate_exact_size(egui::vec2(20.0, 18.0), egui::Sense::hover()); + if let Some([r, g, b]) = rgb(&hex) { + ui.painter().rect_filled(rect, 2.0, egui::Color32::from_rgb(r, g, b)); + } + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + if let Some(typed) = widgets::hex_field(ui, ("hpgl-pen", i), &hex) + && let Some(color) = pen_color(&typed) + { + *v = json!(color); + changed = true; + } + if widgets::icon_button_enabled(ui, "x", tl!("Remove"), false, n > 1, 22.0).clicked() { + remove = Some(i); + } + }); + } + }); + ui.horizontal(|ui| { + ui.add_space(LABEL + 8.0); + if ui.add_enabled(n < MAX_PENS, |ui: &mut egui::Ui| widgets::flat_button(ui, tl!("Add"), 60.0)).clicked() { + // A new pen starts as the last one's color, ready to be changed. + list.push(list.last().cloned().unwrap_or_else(|| json!("#000000"))); + changed = true; + } + }); + if let Some(i) = remove.filter(|_| list.len() > 1) { + list.remove(i); + changed = true; + } + if changed { + d.fields.insert("pens".into(), Value::Array(list)); + } +} + +/// The pens an export from dialog `d` with no pen table would get: its options, artboard choice and +/// source art (the selection with Export Selected Art Only, or when Export Selection opened `d`); +/// an error when there is no document or the export refuses those. +pub(super) fn automatic_pens(app: &VectorcraftApp, d: &Dialog) -> Result, String> { + let st = app.session.active().ok_or("no document")?; + let (doc, params) = source(st, d)?; + fileio::hpgl::automatic_pens(&doc, ¶ms) +} + +/// The document an export from dialog `d` writes and the export params it reads, as +/// [`io::export`] takes them ([`io::take_selection`]): with Export Selection the selection alone, +/// without the artboard choice, else the whole document or, with Export Selected Art Only, its +/// selected objects. +fn source<'a>(st: &'a vectorcraft_engine::DocState, d: &Dialog) -> Result<(std::borrow::Cow<'a, vectorcraft_doc::Document>, Value), String> { + let (selection, params) = io::take_selection(&super::export_as::exported(d, super::form::params(d)))?; + if !selection { + let doc = fileio::export_source(st, ¶ms).map_err(|e| e.to_string())?; + return Ok((doc, params)); + } + let (doc, _) = fileio::selection_doc(st, "document.exportSelection", false).map_err(|e| e.to_string())?; + Ok((std::borrow::Cow::Owned(doc), params)) +} + +/// Choose Pen Table (`on`) or One Pen per Color. Pen Table shows the table set aside when One Pen +/// per Color was chosen, else the pens the export would give the art (`automatic`), else one black +/// pen when that art draws nothing; when `automatic` fails the dialog is left as it was and the +/// error returned. One Pen per Color sets the table aside. +pub(super) fn set_pen_table(d: &mut Dialog, on: bool, automatic: impl FnOnce() -> Result, String>) -> Result<(), String> { + let table = d.fields.get("pens").filter(|v| v.is_array()).cloned(); + match (on, table) { + (true, None) => { + let kept = d.fields.get(SET_ASIDE).filter(|v| v.as_array().is_some_and(|a| !a.is_empty())).cloned(); + let list = match kept { + Some(list) => list, + None => { + let mut pens = automatic()?; + pens.truncate(MAX_PENS); + if pens.is_empty() { + pens.push("#000000".into()); + } + json!(pens) + } + }; + d.fields.remove(SET_ASIDE); + d.fields.insert("pens".into(), list); + } + (false, Some(list)) => { + d.fields.insert(SET_ASIDE.into(), list); + d.fields.insert("pens".into(), Value::Null); + } + _ => {} + } + Ok(()) +} + +/// A typed pen color (`ff0000` or `#FF0000`) as the table holds it, `#ff0000`; `None` unless it is +/// six hex digits. +fn pen_color(typed: &str) -> Option { + let s = typed.trim(); + let s = s.strip_prefix('#').unwrap_or(s); + rgb(s).map(|_| format!("#{}", s.to_ascii_lowercase())) +} + +/// Six hex digits as a color. +fn rgb(hex: &str) -> Option<[u8; 3]> { + if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let byte = |i: usize| hex.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + Some([byte(0)?, byte(2)?, byte(4)?]) +} + +/// Check the options, remember them, and write the file(s). +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = super::form::params(d); + let st = app.session.active().ok_or("no document")?; + // A bad option or artboard choice, nothing selected, or no art to export keeps the dialog open. + let (source, checked) = source(st, d)?; + fileio::hpgl::check(&source, &checked)?; + let remembered = params.as_object().map(|o| o.iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone()))); + let before = std::mem::replace(&mut app.ui.hpgl_options, Value::Object(remembered.into_iter().flatten().collect())); + app.ui.dialog = None; + let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); + let waiting = app.picks.is_waiting(); + let r = io::export(app, Some("hpgl"), path, &super::export_as::exported(d, params)); + if !waiting && app.picks.is_waiting() { + // A save panel shown off the UI thread confirms the dialog again when it answers, which + // remembers the options then; until it does, and when it is canceled, the options + // remembered before stay. + app.ui.hpgl_options = before; + } else if r.is_err() && app.ui.dialog.is_none() { + // An export that stops before writing (a save panel that was canceled or could not be + // shown) leaves the dialog open over the options remembered before. A question that a + // save panel asked stays open. + app.ui.hpgl_options = before; + app.ui.dialog = Some(d.clone()); + } + r +} 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/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 168f5cfda1..c10e5b00bc 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -92,8 +92,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; - if let Some((id, a, b)) = crate::panels::character::text_editing(app) { - crate::panels::character::end_typing(app); + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { targets = json!({"ids": [id.0], "start": a, "end": b}); // After Select All in threaded text: every paragraph of every frame ([`params`]). story = crate::panels::character::text_story(app).map(|_| id.0); 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/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs index c3582ae59a..c0988ec548 100644 --- a/crates/ui-egui/src/dialogs/navigator_panel_options.rs +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -85,7 +85,7 @@ mod tests { d.fields.insert("solidDashes".into(), json!(solid)); super::super::confirm(app) }; - assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true})); + assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true, "viewArtboardContentsOnly": true})); assert!(app.ui.dialog.is_none()); app.run("ui.navigatorPanelOptions", json!({})).unwrap(); set(&mut app, "#0000FF", true).unwrap(); 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 8965564430..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])); } @@ -155,7 +160,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("__otherPpi".into(), json!(i == 3)); } if preset.is_none() - && let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, " ppi", 0, 80.0) + && let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("ppi".into(), json!(v)); } 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/raster_effects.rs b/crates/ui-egui/src/dialogs/raster_effects.rs index cc7ed96f44..d28c30b041 100644 --- a/crates/ui-egui/src/dialogs/raster_effects.rs +++ b/crates/ui-egui/src/dialogs/raster_effects.rs @@ -59,7 +59,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } } if preset.is_none() - && let Some(v) = widgets::plain_field(ui, "raster-ppi", ppi, " ppi", 0, 80.0) + && let Some(v) = widgets::plain_field(ui, "raster-ppi", ppi, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("resolution".into(), json!(v)); } @@ -124,7 +124,7 @@ pub(super) fn effect_fields(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dia } if !document && preset.is_none() - && let Some(v) = widgets::plain_field(ui, "rasterize-ppi", ppi, " ppi", 0, 80.0) + && let Some(v) = widgets::plain_field(ui, "rasterize-ppi", ppi, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("resolution".into(), json!(v)); } diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e3829f92b5..b3cb557b61 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -46,6 +46,22 @@ //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new //! colours as a colour group named `groupName`. //! +//! The Color Groups list on the right (under the tabs in a window too narrow for both; the Show +//! Color Groups button beside the tabs shows or hides it, and it opens shown) lists the document's color groups with their colors. A click on one makes it +//! the group being edited, as opening on it would: with art the art is reduced to as many rows as +//! it has colors, which become their new colors, and without art the rows are its colors. Save +//! Changes rewrites the selected group with the rows' new colors (`swatch.editGroup`, renamed by +//! `groupName`), New Color Group saves them as a new group (`swatch.newGroup`), and Delete removes +//! the selected group with its swatches (`swatch.delete`); each is a step of its own, which the +//! Swatches panel shows. When the art has colors of the group, Save Changes keeps the group's +//! swatches in order: a swatch whose color a row lists takes that row's new color (its own color +//! when the row is excluded), and every other swatch keeps its color. After a save with art the +//! rows' new colors take the Global Adjust, which goes back to 0%. When the save recolors art +//! linked to the group's global swatches, the rows are read from the art again (a color the save +//! gave the art is excluded, and a color the art had before keeps its row's new color). Until the +//! rows or the Global Adjust change, OK changes the saved group only by its name. After a Delete +//! without art, OK saves the rows as a new color group. +//! //! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an //! object takes the palette of the object a Selection tool click takes, a drag takes the palette //! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The @@ -68,8 +84,11 @@ //! show hue and brightness; `hueSaturation`, unset or any other value: hue and saturation), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as //! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as //! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `findColors` (Find is -//! on; it shows the art so on the Assign tab, with art and rows selected). Changing `colors`, a -//! preserve flag or `limitTo` reduces the rows again (and drops `weights`). +//! on; it shows the art so on the Assign tab, with art and rows selected), `groupStorage` (the +//! Color Groups list is shown), `groupAction` (`save`, `new` or `delete`: the list's buttons, +//! checked as the field is set and run by the next frame, or by OK first). Setting `group` to a color group's name selects it in the list, and null +//! selects none. Changing `colors`, a preserve flag or `limitTo` reduces the rows again (and drops +//! `weights`). use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -96,10 +115,25 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, preview: true, min_width: 540.0, - max_width: Some(560.0), + max_width: Some(MAIN_W + STORAGE_GAP + STORAGE_W), + inputs: |_| &[GROUP_ACTION], ..DialogSpec::FORM }; +/// Widths of the dialog's main part (the tabs), of the Color Groups list and of the gap between +/// them; the height of a group's row in the list. +const MAIN_W: f32 = 560.0; +const STORAGE_W: f32 = 170.0; +const STORAGE_GAP: f32 = 12.0; +const GROUP_ROW_H: f32 = 34.0; +/// The fields of the Color Groups list: whether it is shown, a request from its buttons, and the +/// group whose colors the rows were last given. +const GROUP_STORAGE: &str = "groupStorage"; +const GROUP_ACTION: &str = "groupAction"; +const GROUP_LOADED: &str = "__groupLoaded"; +/// The `recolor.reduce` parameters the art's rows were last reduced with. +const REDUCED: &str = "__reduced"; + const CMD: &str = "recolor.apply"; /// Width of the current colours of a row. const CURRENT_W: f32 = 250.0; @@ -182,6 +216,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { "preserveGrays": kept("preserveGrays", false), "limitTo": limit, "group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true, "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, FIND: false, "__art": art, "__assign": assign, "__newGroup": new_group, + GROUP_STORAGE: true, GROUP_LOADED: group, }); let mut d = Dialog::new(KIND, fields); // Without art the rows are there from the start: limit them now (art's rows snap as they reduce). @@ -215,7 +250,7 @@ fn reduce_params(d: &Dialog) -> Value { /// Reduce the art's colours into rows again when the count, preserve flags or library changed /// (assigning a group's colours or the opener's colours as the new colours). fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { - const DONE: &str = "__reduced"; + const DONE: &str = REDUCED; let sig = reduce_params(d); if !d.bool("__art") || d.fields.get(DONE) == Some(&sig) { return; @@ -357,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; @@ -397,7 +433,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator from_colors(r).first().map(key), - Some(_) if adjust.is_identity() => Some(r["to"].clone()), + Some(_) if adjust.is_identity() && palette.is_none() => Some(r["to"].clone()), Some(c) => { let c = adjust.apply(c); Some(key(&palette.as_ref().map_or(c, |p| p.nearest(c)))) @@ -410,7 +446,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator Result<(), String> { let rs = rows(d); let order: Vec = match which { "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(), @@ -418,12 +454,483 @@ fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) { }; let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i))); if colors.is_empty() { - return; + return Ok(()); } // The group is added to the document itself, not to the preview, which runs again afterwards. cancel_preview(app, d); - if let Err(e) = app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})) { - app.status(e); + app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})).map(|_| ()) +} + +/// The colors of the document's color groups, by name, in the Swatches panel's order. +fn doc_groups(app: &VectorcraftApp) -> Vec<(String, Vec)> { + let Some(st) = app.session.active() else { return vec![] }; + st.doc.swatch_groups.iter().map(|g| (g.name.clone(), g.swatches.iter().filter_map(|w| w.paint.color()).collect())).collect() +} + +/// Make the `group` field's color group (none when it is null) the group being edited, when its +/// colors aren't the rows' yet: with art the art is reduced again to as many rows as the group has +/// colors, which become their new colors (as [`open`] does); without art the rows are its colors. +/// A name no color group has is refused, and the field goes back to the group being edited. +fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let want = d.fields.get("group").cloned().unwrap_or(Value::Null); + let loaded = d.fields.get(GROUP_LOADED).cloned().unwrap_or(Value::Null); + if want == loaded { + return Ok(()); + } + // The preview gives the group being edited the name in `groupName`, which the list shows: unless + // the document (without the preview) has another group of that name, it is the same group. + if let Value::String(n) = &want + && loaded.is_string() + && *n == d.str("groupName") + && d.fields.contains_key(super::form::PREVIEWED) + { + cancel_preview(app, d); + if !doc_groups(app).iter().any(|(g, _)| g == n) { + d.fields.insert("group".into(), loaded); + return Ok(()); + } + } + let art = d.bool("__art"); + let name = match &want { + Value::Null => { + // No group: without art OK saves the rows as a new color group. + d.fields.insert(GROUP_LOADED.into(), Value::Null); + if !art { + d.fields.insert("__newGroup".into(), json!(true)); + d.fields.insert("groupName".into(), json!(NEW_GROUP)); + } + return Ok(()); + } + Value::String(n) => n.clone(), + v => { + d.fields.insert("group".into(), loaded); + return Err(format!("`group` must be a color group name, not {v}")); + } + }; + // The group's own colors, not those the preview (which rewrites the group being edited) shows. + if doc_groups(app).iter().any(|(n, _)| *n == name) { + cancel_preview(app, d); + } + let Some((_, colors)) = doc_groups(app).into_iter().find(|(n, _)| *n == name) else { + d.fields.insert("group".into(), loaded); + return Err(format!("no colour group `{name}`")); + }; + let assign: Vec = colors.iter().map(key).collect(); + d.fields.insert(GROUP_LOADED.into(), json!(name)); + d.fields.insert("groupName".into(), json!(name)); + d.fields.insert("__newGroup".into(), json!(false)); + // The group's colors take the place of colors picked with the Color Theme Picker, and the same + // picks made again apply to its rows. + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(THEME_DONE); + d.fields.remove(SAVED_ROWS); + d.fields.remove(SAVED_COLORS); + d.fields.remove(SWATCH_ROWS); + if art { + // The art is reduced again (`sync`) into a row per color of the group. + d.fields.insert("colors".into(), json!(assign.len().max(1))); + d.fields.remove(REDUCED); + } else { + let mut rs: Vec = assign.iter().map(|k| json!({"from": [k], "to": k})).collect(); + snap(app, d, &mut rs); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("__sel".into(), json!([])); + d.fields.remove(COMPS); + } + d.fields.insert("__assign".into(), Value::Array(assign)); + Ok(()) +} + +/// Run a button of the Color Groups list: `save` rewrites the selected group with the rows' new +/// colors as OK gives them to it (with art, followed by the group's colors no row took) and the +/// name in `groupName`; `new` saves the new colors of the rows that aren't excluded as a new group; +/// `delete` removes the selected group and its swatches. Each is an undo step of its own on the +/// document, not on the preview, which runs again afterwards. +fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Result<(), String> { + check_group_action(app, d, action)?; + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // The rows as OK reads them (a group just selected reduces the art again). + sync(app, d); + sync_theme(app, d); + sync_weights(app, d); + match action.as_str() { + Some("new") => save_group(app, d, "all"), + Some("save") if unchanged_since_save(d) => { + // Nothing changed since the last save but perhaps the name. + let name = d.str("groupName"); + if name.trim().is_empty() || group.as_deref() == Some(name.as_str()) { + return Ok(()); + } + cancel_preview(app, d); + let colors: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "rename": name}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + Ok(()) + } + Some("save") => { + let rs = rows(d); + let p = apply_params(d); + // With art, the group's colors no row took follow, adjusted and snapped as OK gives them, + // then the colors added on the Edit tab; a row made with New Row that holds no current + // colors gives the group no color. + cancel_preview(app, d); + let own: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + // An excluded row leaves its swatch the color it has now, as OK's `"keep"` does: with + // art, the swatch's color in `__assign`; without art, the swatch's color in the group, + // which an earlier Save Changes may have changed. + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest: Vec = + p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); + let assign: Vec = + if d.bool("__art") { d.fields.get("__assign").and_then(Value::as_array).cloned().unwrap_or_default() } else { own.clone() }; + let mut colors: Vec = filled + .iter() + .enumerate() + .filter_map(|(i, r)| if excluded(r) { Some(kept_color(&assign, i)) } else { saved_color(app, d, r) }) + .chain(group_colors(app, d, rest.iter())) + .collect(); + // With art in a color of the group, the group keeps its swatch order: a swatch whose row + // ([`swatch_row`]) is found takes that row's new color (its own color when the row is + // excluded), so the art linked to it takes the color its row shows, and every other + // swatch keeps its color. The colors added on the Edit tab follow. + let found: Vec> = (0..own.len()).map(|i| swatch_row(d, &rs, &own, i)).collect(); + let mut links = None; + if d.bool("__art") && found.iter().any(Option::is_some) { + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null()); + let mut saved_links = vec![]; + colors = vec![]; + for (k, f) in own.iter().zip(&found) { + let c = match f { + Some((_, r)) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), + _ => k.clone(), + }; + // A removed swatch leaves the saved group. + if !c.is_null() { + saved_links.push(f.as_ref().map_or(Value::Null, |f| f.0.clone())); + } + colors.push(c); + } + let added = group_colors(app, d, added); + saved_links.extend(added.iter().map(|_| Value::Null)); + colors.extend(added); + links = Some(saved_links); + } + let before = art_colors(app); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "keepModel": true, "rename": p["rename"]}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + // The rows follow the saved group, so a later edit or OK does not remove or add a color + // again: a removed color's row goes (its art keeps its colors). Without art, a color added + // on the Edit tab becomes a row of its own color, after the rows of the group's other + // colors; with art, its row goes and the color is one of the group's colors no row takes. + let art = d.bool("__art"); + let joins = |r: &Value| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null(); + let gone: Vec = + rows(d).iter().filter(|r| color_removed(r)).flat_map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect(); + let (mut joined, mut rs): (Vec, Vec) = rows(d).into_iter().filter(|r| !color_removed(r)).partition(|r| joins(r)); + if art { + joined.clear(); + } + for r in &mut joined { + r["from"] = json!([r["to"].clone()]); + if let Some(o) = r.as_object_mut() { + o.remove("added"); + } + } + // The save added them after the group's other colors, whatever the rows' order. + rs.extend(joined); + if rs != rows(d) { + d.fields.insert("__sel".into(), json!([])); + } + d.fields.insert("rows".into(), Value::Array(rs)); + if art { + // The group's colors no row takes are those of the saved group. + let saved: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| Some(n.as_str()) == r["name"].as_str()) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + d.fields.insert("__assign".into(), Value::Array(saved)); + match links { + Some(l) => d.fields.insert(SWATCH_ROWS.into(), Value::Array(l)), + None => d.fields.remove(SWATCH_ROWS), + }; + // The saved group holds the Global Adjust: the rows' new colors take it, and it goes + // back to 0%, so neither the preview nor OK applies it again. + bake_adjust(app, d); + let rs = rows(d); + if art_colors(app) == before { + mark_saved(app, d); + } else { + reread_rows(app, d, &rs, &before, &gone); + } + } + Ok(()) + } + Some("delete") => { + cancel_preview(app, d); + app.run("swatch.delete", json!({"names": [group]}))?; + d.fields.insert("group".into(), Value::Null); + select_group(app, d) + } + _ => Ok(()), + } +} + +/// The color Save Changes gives the group's swatch for `row`: `null` when the row's color was +/// removed, which removes the swatch as OK does, otherwise its new color as OK gives it. +fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option { + if color_removed(row) { Some(Value::Null) } else { group_colors(app, d, std::iter::once(row)).into_iter().next() } +} + +/// After Save Changes recolored the art linked to the group's global swatches, read the rows from +/// the art again. A row that lists a color the save gave the art (a paint of a selected object +/// that differs from `before`, [`art_colors`] before the save) is excluded with its first color, +/// so the art keeps it, also when other art has that color: `recolor.apply` recolors every use +/// of a color alike, so the row cannot keep that art's earlier new color without undoing the save. Any other row whose first current color one of the `old` rows listed takes +/// that row's new color and exclusion (art the save left as it was keeps its recolor); the rest +/// are excluded too. A row that lists only `gone` colors (those of swatches the save removed) is +/// left out: its art keeps its colors, and the row gives the group no color. +fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec], gone: &[Value]) { + let given: Vec = + art_colors(app).iter().zip(before).flat_map(|(now, was)| now.iter().zip(was).filter(|(n, w)| n != w).map(|(n, _)| n.clone())).collect(); + // A swatch whose color the save gave the art is found by that color again: the row its old + // color found lists other art now. + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + if let Some(Value::Array(links)) = d.fields.get_mut(SWATCH_ROWS) { + for (l, c) in links.iter_mut().zip(&saved) { + if given.contains(c) { + *l = Value::Null; + } + } + } + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(REDUCED); + sync(app, d); + let mut rs = rows(d); + for r in &mut rs { + let Some(first) = r["from"].as_array().and_then(|f| f.first()).cloned() else { continue }; + let from_save = r["from"].as_array().is_some_and(|f| f.iter().any(|c| given.contains(c))); + match row_listing(old, &first).filter(|_| !from_save) { + Some(o) => { + r["to"] = o["to"].clone(); + r["exclude"] = json!(excluded(o)); + } + None => { + r["to"] = first; + r["exclude"] = json!(true); + } + } + } + rs.retain(|r| r["from"].as_array().is_none_or(|f| f.is_empty() || !f.iter().all(|c| gone.contains(c)))); + d.fields.insert("rows".into(), Value::Array(rs)); + mark_saved(app, d); +} + +/// Give each row's new color the Global Adjust (and Limit to Library) as OK would, and set the +/// Global Adjust back to 0%; nothing changes when it is 0%. +fn bake_adjust(app: &VectorcraftApp, d: &mut Dialog) { + if global_adjust(adjust_values(d)).is_identity() { + return; + } + let mut rs = rows(d); + for r in &mut rs { + if to_color(r).is_some() + && let Some(c) = group_colors(app, d, std::iter::once(&*r)).into_iter().next() + { + r["to"] = c; + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().map(|k| (k.to_string(), json!(0.0))).collect())); +} + +/// After Save Changes with art: until the rows or the Global Adjust change, OK and the preview +/// leave the selected group's colors as they were saved. +fn mark_saved(app: &VectorcraftApp, d: &mut Dialog) { + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + d.fields.insert(SAVED_COLORS.into(), Value::Array(saved)); + d.fields.insert(SAVED_ROWS.into(), Value::Array(rows(d))); + d.fields.insert(SAVED_ADJUST.into(), json!(adjust_values(d))); +} + +/// Whether the rows and the Global Adjust are as [`mark_saved`] recorded them. +fn unchanged_since_save(d: &Dialog) -> bool { + d.fields.get(SAVED_ROWS).and_then(Value::as_array).is_some_and(|s| *s == rows(d)) + && d.fields.get(SAVED_ADJUST).is_some_and(|a| *a == json!(adjust_values(d))) +} + +/// The Global Adjust amounts [`mark_saved`] recorded. +const SAVED_ADJUST: &str = "__savedAdjust"; + +/// The colors of each selected object and what is inside it, as row keys, in paint order. +fn art_colors(app: &VectorcraftApp) -> Vec> { + let Some(st) = app.session.active() else { return vec![] }; + st.selection + .objects + .iter() + .map(|id| { + let mut cs = vec![]; + if let Some(n) = st.doc.node(*id) { + vectorcraft_doc::swatches::node_colors(n, &mut |c, _| cs.push(key(c))); + } + cs + }) + .collect() +} + +/// The rows [`mark_saved`] recorded after Save Changes; while the rows are these, OK and the preview +/// leave the group's colors as saved ([`SAVED_COLORS`]) and change only its name. +const SAVED_ROWS: &str = "__savedRows"; + +/// The selected group's colors after Save Changes. OK with a new name keeps the color of each of +/// those swatches (`"keep"`). +const SAVED_COLORS: &str = "__savedColors"; + +/// With art, for each swatch of the selected group after Save Changes, the color that found the row +/// that gave it its new color (`null` for a swatch no row gave one), so a later Save Changes or OK +/// finds that row again when the row still lists its old current color. +const SWATCH_ROWS: &str = "__swatchRows"; + +/// The row that gives the swatch at place `i` of `own` (the group's colors) its new color, with the +/// color that finds it: the row listing the color [`SWATCH_ROWS`] holds for that swatch, else the +/// first row listing the swatch's own color. +fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Option<(Value, &'a Value)> { + let links = d.fields.get(SWATCH_ROWS).and_then(Value::as_array).filter(|l| l.len() == own.len()); + let link = links.and_then(|l| l.get(i)).filter(|l| !l.is_null()); + link.and_then(|l| row_listing(rs, l).map(|r| (l.clone(), r))).or_else(|| own.get(i).and_then(|k| row_listing(rs, k).map(|r| (k.clone(), r)))) +} + +/// The color an excluded row leaves its swatch, the row being the `i`th of the rows with current +/// colors: the swatch's own color in `assign` (the group's colors), else `null`, which adds no +/// swatch past the group's, as OK's `"keep"` does. +fn kept_color(assign: &[Value], i: usize) -> Value { + assign.get(i).cloned().unwrap_or(Value::Null) +} + +/// Refuse a `groupAction` other than `save`, `new` or `delete`, `save` or `delete` with no group +/// selected, and `save` on a group with a swatch that is not a color (a gradient, pattern or None +/// swatch): the rows hold only the group's colors, so the save would replace or remove it. +fn check_group_action(app: &VectorcraftApp, d: &Dialog, action: &Value) -> Result<(), String> { + let group = d.fields.get("group").and_then(Value::as_str); + match (action.as_str(), group) { + (Some("new"), _) => Ok(()), + (Some("save"), Some(g)) if holds_other_paints(app, g) => { + Err(format!("color group `{g}` holds swatches that are not colors, which Save Changes can't keep")) + } + (Some("save" | "delete"), Some(_)) => Ok(()), + (Some("save" | "delete"), None) => Err("missing `group`".into()), + _ => Err(format!("`{GROUP_ACTION}` must be \"save\", \"new\" or \"delete\", not {action}")), + } +} + +/// Whether color group `group` has a swatch that is not a color, in the document as it is without +/// the preview (which can rewrite or rename the group). +fn holds_other_paints(app: &VectorcraftApp, group: &str) -> bool { + let Some(st) = app.session.active() else { return false }; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + doc.swatch_groups.iter().any(|g| g.name == group && g.swatches.iter().any(|w| w.paint.color().is_none())) +} + +/// Run the button of the Color Groups list that `groupAction` holds, if any. +fn run_group_action(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + match d.fields.remove(GROUP_ACTION) { + Some(a) => group_action(app, d, &a), + None => Ok(()), + } +} + +/// `ui.dialog.set` of `group`, `groupStorage` or `groupAction`: select the group, or check the +/// button, which the next frame (or OK) runs. +pub(super) fn field_set(app: &mut VectorcraftApp, field: &str) -> Result<(), String> { + let Some(mut d) = app.ui.dialog.take() else { return Ok(()) }; + let r = match field { + "group" => select_group(app, &mut d), + GROUP_ACTION => match d.fields.get(GROUP_ACTION).cloned() { + Some(a) => check_group_action(app, &d, &a), + None => Ok(()), + }, + GROUP_STORAGE if !d.fields.get(GROUP_STORAGE).is_some_and(Value::is_boolean) => Err(format!("`{GROUP_STORAGE}` must be true or false")), + _ => Ok(()), + }; + app.ui.dialog = Some(d); + r +} + +/// The Color Groups list: a row per color group of the document with its name and colors (a click +/// selects it), and the Save Changes, New Color Group and Delete buttons under it. +fn group_storage(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, max_h: f32) { + let t = Tokens::get(ui.ctx()); + let groups = doc_groups(app); + let mut current = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // While the art previews, the group being edited shows under its new name. + if current.is_some() && d.fields.contains_key(super::form::PREVIEWED) && !groups.iter().any(|(n, _)| Some(n) == current.as_ref()) { + current = Some(d.str("groupName")); + } + let mut picked = None; + egui::ScrollArea::vertical().id_salt("recolor-groups").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| { + for (name, colors) in &groups { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_ROW_H), Sense::click()); + let on = current.as_deref() == Some(name.as_str()); + if on { + ui.painter().rect_filled(r, 2.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.hover); + } + let inner = r.shrink2(vec2(4.0, 3.0)); + ui.painter().text(inner.left_top(), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(12.0), t.text); + let fit = ((inner.width() + 2.0) / 12.0).floor().max(0.0) as usize; + for (n, c) in colors.iter().take(fit).enumerate() { + let x = inner.left() + n as f32 * 12.0; + chip(ui, Rect::from_min_size(pos2(x, inner.bottom() - 10.0), vec2(10.0, 10.0)), *c, false); + } + let resp = resp.on_hover_text(name); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), on, name)); + if resp.clicked() { + picked = Some(name.clone()); + } + } + }); + if let Some(name) = picked { + d.fields.insert("group".into(), json!(name)); + if let Err(e) = select_group(app, d) { + app.status(e); + } + } + ui.add_space(4.0); + let selected = current.is_some(); + let any = rows(d).iter().any(|r| !excluded(r)); + let mut action = None; + ui.horizontal(|ui| { + if widgets::icon_button_enabled(ui, "save", tl!("Save Changes"), false, selected, 24.0).clicked() { + action = Some("save"); + } + if widgets::icon_button_enabled(ui, "dc-folder", tl!("New Color Group"), false, any, 24.0).clicked() { + action = Some("new"); + } + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete"), false, selected, 24.0).clicked() { + action = Some("delete"); + } + }); + if let Some(a) = action { + d.fields.insert(GROUP_ACTION.into(), json!(a)); } } @@ -580,6 +1087,12 @@ fn no_current(row: &Value) -> bool { row["from"].as_array().is_none_or(Vec::is_empty) } +/// Whether `row` holds current colors and its new color was removed (`to: null`) and isn't excluded: +/// its swatch in the color group is removed. +fn color_removed(row: &Value) -> bool { + !excluded(row) && !no_current(row) && row["to"].is_null() +} + /// Whether `row` is a color added on the Edit tab (`added`), which joins the color group. fn is_added(row: &Value) -> bool { row["added"].as_bool().unwrap_or(false) @@ -609,21 +1122,47 @@ fn selection(d: &Dialog) -> Vec { /// `recolor.apply` parameters: the rows, method, library and the group with its new name and /// colors: the new colors of the rows with current colors, each in its swatch's place (`null` -/// for a row whose new color was removed, which removes its swatch), then (with art) the group's -/// colors no row took, then the colors added on the Edit tab. +/// for a row whose new color was removed, which removes its swatch, and `"keep"` for an excluded +/// row, which leaves its swatch its color), then (with art) the group's colors no row took, then the +/// colors added on the Edit tab. With art in a color of the group, each swatch whose row +/// ([`swatch_row`]) is found takes that row's new color instead, and every other swatch keeps its +/// color, as Save Changes gives them. fn apply_params(d: &Dialog) -> Value { let rs = rows(d); - let group = d.fields.get("group").and_then(Value::as_str).map(|g| { - // A row made with New Row that holds no current colors gives the group no color; a color - // added on the Edit tab (`added`) joins it after the others. - let took: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).map(|r| &r["to"]).collect(); - let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")); - let rest = assign.map_or(&[][..], |a| a.get(took.len()..).unwrap_or_default()); - let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null()); - let colors: Vec<&Value> = took.into_iter().chain(rest).chain(added).collect(); + // The rows and Global Adjust unchanged since Save Changes: the group keeps its saved colors. + let saved = unchanged_since_save(d); + let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).map_or(&[][..], Vec::as_slice); + let found: Vec> = (0..assign.len()).map(|i| swatch_row(d, &rs, assign, i)).collect(); + let keep = json!("keep"); + let group = d.fields.get("group").and_then(Value::as_str).and_then(|g| { let name = d.str("groupName"); let rename = (!name.trim().is_empty() && name != g).then_some(name); - json!({"group": g, "groupColors": colors, "rename": rename}) + let colors: Vec<&Value> = if saved { + // Only a new name changes the group: each swatch keeps its exact color. + rename.as_ref()?; + d.fields.get(SAVED_COLORS).and_then(Value::as_array).map(|a| a.iter().map(|_| &keep).collect())? + } else { + // A row made with New Row that holds no current colors gives the group no color; a color + // added on the Edit tab (`added`) joins it after the others. + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null()); + // A swatch that keeps its color takes no Global Adjust. + if found.iter().any(Option::is_some) { + found + .iter() + .map(|f| match f { + Some((_, r)) if !excluded(r) => &r["to"], + _ => &keep, + }) + .chain(added) + .collect() + } else { + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest = assign.get(filled.len()..).unwrap_or_default(); + let took = filled.iter().map(|r| if excluded(r) { &keep } else { &r["to"] }); + took.chain(rest).chain(added).collect() + } + }; + Some(json!({"group": g, "groupColors": colors, "rename": rename})) }); // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); @@ -661,6 +1200,26 @@ fn find_entry(k: &Value) -> Option { } } +/// The first of `rows` that lists the color entry `k`, as `recolor.apply` reads entries: rows that +/// list it as an exact color (by key, whatever its case or spacing) come before rows whose +/// "#rrggbb" entry matches it by its hex. Rows that give the color a new color (not excluded, `to` +/// not `null`) come first, since `recolor.apply` maps the color with them; an excluded row or one +/// that removes the color is found only when no such row lists it. +fn row_listing<'a>(rows: &'a [Value], k: &Value) -> Option<&'a Value> { + let want = find_entry(k)?; + let hex = |e: &FindEntry| e.as_ref().map_or_else(Clone::clone, |k| k.color().to_hex()); + let lists = |r: &Value, by_hex: bool| { + r["from"].as_array().is_some_and(|f| { + f.iter().filter_map(find_entry).any(|e| match (&e, &want) { + (Ok(a), Ok(b)) => !by_hex && a == b, + _ => by_hex && hex(&e) == hex(&want), + }) + }) + }; + let find = |live: bool, by_hex: bool| rows.iter().filter(|r| !live || (!excluded(r) && !r["to"].is_null())).find(|r| lists(r, by_hex)); + find(true, false).or_else(|| find(true, true)).or_else(|| find(false, false)).or_else(|| find(false, true)) +} + /// While Find is on, on the Assign tab with art and rows selected: what the art previews instead of /// [`apply_params`], as `command.batch` parameters. A first `recolor.apply` gives each current color /// of the rows that aren't selected, and each preserved color, its [`FIND_DIM`] tint, or the nearest lighter one when that is a @@ -734,10 +1293,57 @@ fn find_params(d: &Dialog) -> Option { (!commands.is_empty()).then(|| json!({"commands": commands})) } +/// The tabs, and the Color Groups list on their right while it is shown. fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + if let Err(e) = select_group(app, d) { + app.status(e); + } + let room = ui.available_width(); + // Without the room for both side by side (a narrow window), the list goes under the tabs. + let beside = room >= SPEC.min_width + STORAGE_GAP + STORAGE_W; + // The Color Picker that a double-click on a new color or Pick from Swatches asks for opens over + // the dialog after the list is drawn, so the window keeps its size while the picker is open. + let mut picker = None; + if !d.bool(GROUP_STORAGE) || !beside { + ui.vertical(|ui| { + ui.set_width(room.min(MAIN_W)); + picker = main(app, ui, d); + if d.bool(GROUP_STORAGE) { + ui.add_space(6.0); + group_storage(app, ui, d, 3.0 * GROUP_ROW_H); + } + }); + } else { + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width((room - STORAGE_GAP - STORAGE_W).clamp(0.0, MAIN_W)); + picker = main(app, ui, d); + }); + ui.add_space(STORAGE_GAP); + ui.vertical(|ui| { + ui.set_width(STORAGE_W); + group_storage(app, ui, d, TAB_H - 30.0); + }); + }); + } + if let Some((i, swatches)) = picker + && let Some(row) = rows(d).get(i) + { + let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); + *d = super::color_picker::over_recolor(d, c, i, swatches); + } + false +} + +/// The tabs and the controls under them. Returns the row whose new color a double-click or Pick +/// from Swatches asked to pick in the Color Picker, with `true` for Pick from Swatches. +fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, bool)> { sync(app, d); sync_theme(app, d); sync_weights(app, d); + if let Err(e) = run_group_action(app, d) { + app.status(e); + } let t = Tokens::get(ui.ctx()); let picking = d.bool(THEME_PICKER); ui.horizontal(|ui| { @@ -751,6 +1357,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() { d.fields.insert(THEME_PICKER.into(), json!(!picking)); } + let storage = d.bool(GROUP_STORAGE); + if widgets::icon_button(ui, "library", tl!("Show Color Groups"), storage, 24.0).clicked() { + d.fields.insert(GROUP_STORAGE.into(), json!(!storage)); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. if let Some(i) = widgets::dropdown_named(ui, "recolor-preset", Some(tl!("Preset:")), PRESETS[preset_of(d)], &PRESETS, 130.0) { @@ -782,8 +1392,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { d.fields.insert("rows".into(), Value::Array(rs)); } sync_weights(app, d); - if let Some(which) = d.fields.remove(SAVE_GROUP) { - save_group(app, d, which.as_str().unwrap_or_default()); + if let Some(which) = d.fields.remove(SAVE_GROUP) + && let Err(e) = save_group(app, d, which.as_str().unwrap_or_default()) + { + app.status(e); } if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") { ui.add_space(6.0); @@ -804,13 +1416,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { None => form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)), } } - if let Some((i, swatches)) = pick - && let Some(row) = rows(d).get(i) - { - let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); - *d = super::color_picker::over_recolor(d, c, i, swatches); - } - false + pick } /// `d` with row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -829,9 +1435,19 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C /// save colours opened alone as a new colour group). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); + select_group(app, &mut d)?; sync(app, &mut d); sync_theme(app, &mut d); sync_weights(app, &mut d); + // A Color Groups button set with OK in one request runs first, once: the open dialog takes + // its result, so an OK that fails afterwards does not run it again. + if d.fields.contains_key(GROUP_ACTION) { + let r = run_group_action(app, &mut d); + if let Some(live) = app.ui.dialog.as_mut().filter(|x| x.kind == KIND) { + *live = d.clone(); + } + r?; + } if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r))); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); @@ -1334,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, @@ -2000,14 +2616,14 @@ mod tests { } /// Opened on a color group, OK rewrites it with the new colors of the rows that hold current - /// colors, then the group's colors no such row took: an empty row gives it no color. + /// colors, and the group's color no such row lists keeps its color: an empty row gives it no color. #[test] fn an_empty_row_gives_the_group_no_color() { let mut r = rows(); new_row(&mut r, &[]); let fields = json!({"rows": r, "group": "Trio", "__art": true, "__assign": ["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"]}); let p = apply_params(&Dialog::new("recolor", fields)); - assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"])); + assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "keep"])); } /// Opened on colors alone, OK saves the new colors of the rows that hold current colors as the @@ -2032,6 +2648,37 @@ mod tests { } /// Randomize after a seed past `u64::MAX` keeps the largest seed. + /// A row that lists a color exactly comes before an earlier row whose "#rrggbb" entry matches + /// it, as `recolor.apply` reads them; a hex entry matches a key of the same hex. + #[test] + fn a_row_listing_a_color_exactly_comes_before_a_hex_match() { + let rs = + [json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), json!({"from": ["RGB 0 0 255"], "to": "rgb 255 0 0"}), json!({"from": ["#ff0000"]})]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[1])); + assert_eq!(row_listing(&rs, &json!("rgb 255 0 0")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("#ff0000")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("rgb 0 255 0")), None); + assert_eq!(row_listing(&rs, &json!("cmyk 0 0 0 0")), None); + } + + /// A row that gives a color a new color comes before an earlier row that removes it or is + /// excluded, exact or by hex, as `recolor.apply` maps the color with it; those rows are found + /// only when no such row lists the color. + #[test] + fn a_row_giving_a_color_a_new_color_comes_before_one_removing_it() { + let rs = [ + json!({"from": ["rgb 0 0 255"], "to": null}), + json!({"from": ["rgb 0 0 255"], "to": "rgb 0 0 0", "exclude": true}), + json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), + json!({"from": ["rgb 0 0 255"], "to": "rgb 255 0 0"}), + json!({"from": ["rgb 255 255 0"], "to": null}), + ]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[3])); + assert_eq!(row_listing(&rs[..3], &json!("rgb 0 0 255")), Some(&rs[2]), "by hex"); + assert_eq!(row_listing(&rs[..2], &json!("rgb 0 0 255")), Some(&rs[0])); + assert_eq!(row_listing(&rs, &json!("rgb 255 255 0")), Some(&rs[4])); + } + #[test] fn next_seed_holds_at_the_largest() { assert_eq!(next_seed(&Dialog::new("recolor", json!({}))), 1); @@ -2801,4 +3448,845 @@ mod tests { let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), [Color::rgb8(255, 128, 0)]); } + + /// Sets `field` of the open dialog to `value` as `ui.dialog.set` does: a refused value leaves + /// the dialog as it was. + fn set(app: &mut VectorcraftApp, field: &str, value: Value) -> Result<(), String> { + let before = app.ui.dialog.clone(); + let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(field).cloned()); + if let Some(d) = app.ui.dialog.as_mut() { + crate::dialogs::set_field(d, field.into(), value); + } + let r = crate::dialogs::field_set(app, field, old.as_ref()); + if r.is_err() { + app.ui.dialog = before; + } + r + } + + fn group_hex(app: &VectorcraftApp, name: &str) -> Option> { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect()) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// Sets `groupAction` to `a` as `ui.dialog.set` does and draws the frame that runs it. + fn act(app: &mut VectorcraftApp, ctx: &egui::Context, t: f64, a: &str) -> Result<(), String> { + set(app, GROUP_ACTION, json!(a))?; + frame(app, ctx, t, vec![], 0); + Ok(()) + } + + /// Without art: a group picked in the Color Groups list (the `group` field) gives the rows its + /// colors, and a name no group has is refused. Save Changes rewrites the selected group with the + /// rows' new colors and the name field, as one step, and records none when nothing changes; + /// Delete removes it, after which OK saves the rows as a new group; New Color Group adds one. + #[test] + fn the_color_groups_list_selects_saves_and_deletes_groups() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], true, "the list opens shown"); + + set(&mut app, "group", json!("B")).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("groupName"), "B"); + assert_eq!(set(&mut app, "group", json!("Nope")), Err("no colour group `Nope`".into())); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "B", "a refused name leaves B selected"); + assert!(set(&mut app, GROUP_STORAGE, json!("yes")).is_err()); + assert!(set(&mut app, GROUP_ACTION, json!("rename")).is_err()); + + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("groupName".into(), json!("Night")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Night"), Some(vec!["#000000".into(), "#ffff00".into(), "#ffffff".into()])); + assert_eq!(group_hex(&app, "B"), None, "renamed"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "Night"); + assert_eq!(undo_len(&app), undo + 1, "one step"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(undo_len(&app), undo + 1, "saving the same colors again records no step"); + + act(&mut app, &ctx, 0.3, "delete").unwrap(); + assert_eq!(group_hex(&app, "Night"), None); + assert_eq!(undo_len(&app), undo + 2); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.fields["group"].is_null() && d.bool("__newGroup"), "{:?}", d.fields); + assert_eq!(act(&mut app, &ctx, 0.4, "delete"), Err("missing `group`".into())); + assert_eq!(act(&mut app, &ctx, 0.5, "save"), Err("missing `group`".into())); + assert_eq!(undo_len(&app), undo + 2, "a refused button records no step"); + + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + act(&mut app, &ctx, 0.6, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), n + 1); + let last: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + assert_eq!(last, ["#000000", "#ffff00", "#ffffff"]); + assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); + } + + /// Without art: after a group is picked in the list, the same Color Theme Picker picks that gave + /// the group before it its colors give the new group's rows the palette of the art picked too. + #[test] + fn theme_picks_apply_again_after_another_group_is_picked() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + square(&mut app, 100.0, "#00ff00"); + app.run("select.set", json!({"ids": []})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let picks = json!([{"at": [107, 17]}]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks.clone()); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); + set(&mut app, "group", json!("B")).unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0"), json!("rgb 0 255 0")], "the picks apply to B's rows"); + } + + /// Save Changes on a group with a swatch that is not a color is refused, renamed or not, and + /// leaves the group as it is: the rows hold only its colors. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.insert(1, fade_swatch()); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + 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.1, "save"), refused); + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Renamed")); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + // OK first runs a save set together with it, and the dialog stays open. + app.ui.dialog.as_mut().unwrap().fields.insert(GROUP_ACTION.into(), json!("save")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches[1], fade_swatch(), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#00ff00".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// A gradient swatch, for a color group. + fn fade_swatch() -> vectorcraft_color::Swatch { + let paint = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default()))); + vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false } + } + + /// 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() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.push(fade_swatch()); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + 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.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); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches.last(), Some(&fade_swatch()), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// Save Changes on a group whose global swatches the selected art is linked to: the art takes + /// the group's new colors, and the rows are read from the art again, so they list its colors as + /// they are now. A color the art had before keeps its row's new color; a color the save gave + /// it stays as it is. + #[test] + fn saving_a_group_the_art_links_to_reads_the_rows_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + // The rows took the group's colors in their order, so one of the swatches is now green. + let saved = group_hex(&app, "Linked").unwrap(); + assert!(saved.len() == 2 && saved.contains(&"#008000".to_string()), "{saved:?}"); + let mut want = saved.clone(); + want.sort(); + assert_eq!(fill_hex(&app, red), "#008000", "the red square keeps the new color its row gave it"); + for r in super::rows(app.ui.dialog.as_ref().unwrap()) { + if !from_colors(&r).iter().any(|c| ["#ff0000", "#0000ff"].contains(&c.to_hex().as_str())) { + assert!(excluded(&r) && r["to"] == r["from"][0], "a color the save gave the art stays: {r}"); + } + } + let mut froms: Vec = super::rows(app.ui.dialog.as_ref().unwrap()).iter().flat_map(from_colors).map(|c| c.to_hex()).collect(); + froms.sort(); + assert_eq!(froms, want, "the rows list the art's colors as they are now"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + // OK with only a new name keeps the preview as one step and renames the group, keeping its + // saved colors. + let undo = undo_len(&app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Renamed"), Some(saved)); + assert_eq!(group_hex(&app, "Linked"), None); + assert_eq!(fill_hex(&app, red), "#008000"); + assert_eq!(undo_len(&app), undo + 1); + } + + /// OK with only a new name after Save Changes leaves every swatch of the group its exact color: + /// a CMYK swatch no row lists keeps components finer than a hundredth of a percent. + #[test] + fn renaming_a_saved_group_keeps_its_exact_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let fine = Color::cmyk(0.123_456, 0.654_321, 0.0, 0.010_101); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Linked").unwrap(); + g.swatches.push(vectorcraft_color::Swatch { name: "Fine".into(), paint: vectorcraft_color::Paint::solid(fine), global: false, spot: false }); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let swatches = |app: &VectorcraftApp, name: &str| { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect::>()) + }; + let saved = swatches(&app, "Linked").unwrap(); + assert_eq!(saved.last(), Some(&Some(fine)), "Save Changes keeps the swatch no row lists"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(swatches(&app, "Renamed"), Some(saved), "the rename keeps every color exactly"); + } + + /// Save Changes where one row's new color is another row's current color: the art linked to the + /// group keeps the colors the save gave it, and is not recolored again by the other row; a + /// Global Adjust set afterwards gives OK the group again. + #[test] + fn saving_a_group_keeps_the_colors_it_gave_the_linked_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let from = from_colors(r).first().map(|c| c.to_hex()); + r["to"] = match from.as_deref() { + Some("#ff0000") => json!("rgb 0 0 255"), + _ => json!("rgb 0 128 0"), + }; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let mut group = group_hex(&app, "Linked").unwrap(); + group.sort(); + let mut fills = vec![fill_hex(&app, red), fill_hex(&app, blue)]; + fills.sort(); + assert_eq!(fills, group, "the art shows the saved group's colors, not a second recolor"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none()); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_some(), "a new Global Adjust rewrites the group at OK"); + } + + /// Save Changes with art in only some colors of the group: the swatches keep their order, and a + /// swatch no row lists keeps its color. + #[test] + fn saving_a_group_keeps_the_swatches_the_art_does_not_use() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the swatches keep their order and the red one its color"); + assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); + } + + /// Save Changes with art in colors of the group keeps the Edit tab's changes: a removed color's + /// swatch is removed, and a color added on the Edit tab joins the group after the others. + #[test] + fn saving_a_group_keeps_added_and_removed_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 0 128 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let mut want: Vec = order.into_iter().filter(|h| h != "#0000ff").collect(); + want.push("#008000".into()); + assert_eq!(group_hex(&app, "Linked"), Some(want.clone()), "the removed swatch goes and the added color follows the others"); + assert_eq!(fill_hex(&app, blue), "#0000ff", "art linked to a removed swatch keeps its color"); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + assert!(rs.iter().all(|r| !r["to"].is_null() && !is_added(r)), "the rows follow the saved group: {rs:?}"); + let assign = app.ui.dialog.as_ref().unwrap().fields["__assign"].clone(); + let assign: Vec = assign.as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + assert_eq!(Some(assign), group_hex(&app, "Linked"), "a later edit gives the group no removed swatch back"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "OK removes and adds nothing more"); + } + + /// Save Changes that recolors linked art reads the rows from the art again; a color added on the + /// Edit tab stays one of the group's colors and a removed one does not come back, so OK after a + /// further edit keeps them as saved. + #[test] + fn saving_a_group_that_reads_the_rows_again_keeps_an_added_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let lime = square(&mut app, 70.0, "#00ff00"); + app.run("select.set", json!({"ids": [red, blue, lime]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#ff0000") => json!("rgb 0 128 0"), + Some("#00ff00") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(fill_hex(&app, red), "#008000", "the save recolored the linked art"); + assert_eq!(fill_hex(&app, lime), "#00ff00", "art linked to the removed swatch keeps its color"); + let group = group_hex(&app, "Linked").unwrap(); + assert!(group.contains(&"#ffff00".to_string()) && !group.contains(&"#00ff00".to_string()), "{group:?}"); + let mut d = app.ui.dialog.clone().unwrap(); + let mut rs = super::rows(&d); + assert!(rs.iter().all(|r| !is_added(r)), "{rs:?}"); + if let Some(r) = rs.last_mut() { + r["to"] = json!("rgb 10 10 10"); + } + d.fields.insert("rows".into(), Value::Array(rs)); + let colors = sent_by(&app, &d); + assert_eq!(colors.iter().filter(|c| *c == "#ffff00").count(), 1, "OK after a further edit keeps the added color once: {colors:?}"); + assert!(!colors.contains(&"#00ff00".to_string()), "nor brings the removed color back: {colors:?}"); + } + + /// Save Changes where the rows list their current colors as "#rrggbb": a row matches the swatch + /// of the same color, so the swatches keep their order and the one a row lists takes its new + /// color; read again afterwards, a row whose old entry was a hex keeps its new color. + #[test] + fn saving_a_group_matches_rows_that_list_hex_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + let orange = square(&mut app, 100.0, "#ff8000"); + app.run("select.set", json!({"ids": [blue, yellow, orange]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let hex: Vec = from_colors(r).iter().map(|c| c.to_hex()).collect(); + r["to"] = match hex.first().map(String::as_str) { + Some("#0000ff") => json!("rgb 0 128 0"), + Some("#ff8000") => json!("rgb 128 0 128"), + _ => r["from"][0].clone(), + }; + r["from"] = json!(hex); + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the blue swatch takes the green, the red one keeps its color"); + assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#008000".into())); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + let o = rs.iter().find(|r| from_colors(r).iter().any(|c| c.to_hex() == "#ff8000")).unwrap(); + assert!(!excluded(o) && o["to"] == json!("rgb 128 0 128"), "the orange row keeps its new color: {o}"); + } + + /// Save Changes with art in the group's colors that is not linked to its swatches: the art is + /// left to the preview, and OK leaves the saved group as it is until the rows change. + #[test] + fn saving_a_group_with_unlinked_art_keeps_the_saved_group_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(fill_hex(&app, blue), "#008000", "the art previews its row's new color"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + } + + /// The colors `d`'s OK gives the selected group, as hex, `"keep"` read as the color the swatch + /// at its place has. + fn sent_by(app: &VectorcraftApp, d: &Dialog) -> Vec { + let own = group_hex(app, &d.str("group")).unwrap_or_default(); + let p = apply_params(d); + let hex = |(i, k): (usize, &Value)| if *k == json!("keep") { own.get(i).cloned() } else { color_value(k).map(|c| c.to_hex()) }; + p["groupColors"].as_array().unwrap().iter().enumerate().filter_map(hex).collect() + } + + /// The colors OK gives the selected group, as [`sent_by`] reads them. + fn sent_hex(app: &VectorcraftApp) -> Vec { + sent_by(app, app.ui.dialog.as_ref().unwrap()) + } + + /// Sets the new color of the rows whose first current color is `hex` to `to`. + fn set_row(app: &mut VectorcraftApp, hex: &str, to: Value) { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some(hex) { + r["to"] = to.clone(); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + } + + /// With unlinked art in some of the group's colors, a second Save Changes after a further edit of + /// a row gives the swatch the first save gave that row's color the row's new color, and OK does + /// too; the swatch no row lists keeps its color both times. + #[test] + fn saving_a_group_twice_with_unlinked_art_gives_a_row_its_swatch_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff", "#ffff00"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + set_row(&mut app, "#ffff00", json!("rgb 255 255 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into(), "#ffff00".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 128 0 128")); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#800080", "#ffff00"], "OK gives the blue row's swatch its new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#800080".into(), "#ffff00".into()]), "the second save does too"); + } + + /// Without art, an excluded row leaves its swatch its own color at Save Changes and at OK, even + /// when its new color was changed before it was excluded. + #[test] + fn saving_a_group_without_art_keeps_an_excluded_rows_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#ff0000") { + r["to"] = json!("rgb 0 128 0"); + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#0000ff"], "OK keeps the excluded row's swatch"); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert_eq!(p["groupColors"][0], "keep", "so the Global Adjust leaves it as it is too: {p}"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); + } + + /// With art in more colors than the group has swatches, an excluded row past the swatches adds + /// no color at Save Changes, as at OK. + #[test] + fn saving_a_group_with_art_adds_no_color_for_an_excluded_row_past_its_swatches() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("colors".into(), json!(2)); + d.fields.remove(REDUCED); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + assert_eq!(rs.len(), 2, "a row for each color of the art: {rs:?}"); + for r in &mut rs { + r["exclude"] = json!(true); + } + d.fields.insert("rows".into(), Value::Array(rs)); + // `recolor.apply` adds nothing for a "keep" past the group's swatches. + assert_eq!(apply_params(app.ui.dialog.as_ref().unwrap())["groupColors"], json!(["keep", "keep"]), "OK adds no color"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into()]), "Save Changes adds none either"); + } + + /// Without art, a row excluded after Save Changes gave its swatch a new color leaves the swatch + /// that saved color at a second Save Changes, as OK does. + #[test] + fn saving_a_group_without_art_keeps_a_saved_color_when_its_row_is_excluded() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["to"] == json!("rgb 0 128 0") { + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#008000", "#0000ff"], "OK keeps the saved color"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()]), "so does a second Save Changes"); + } + + /// Save Changes that recolors linked art so that one swatch takes another swatch's old color: + /// read again, the row of the second swatch's new color gives that swatch a later new color. + #[test] + fn saving_a_group_twice_with_linked_art_finds_the_row_of_a_swatchs_new_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 0 255")); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#008000".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#008000") { + r["to"] = json!("rgb 128 0 128"); + r["exclude"] = json!(false); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#0000ff", "#800080"], "OK gives the green swatch the green row's new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#800080".into()]), "so does Save Changes"); + } + + /// Save Changes with a Global Adjust: the saved group holds it, the rows' new colors take it and + /// it goes back to 0%, so OK with a new name renames the group without adjusting it again. + #[test] + fn saving_a_group_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(adjust_values(d), [0.0; 4]); + d.fields.insert("groupName".into(), json!("Dark")); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert!(p.get("globalAdjust").is_none(), "{p}"); + assert_eq!(p["groupColors"], json!(vec!["keep"; saved.len()]), "OK keeps each saved color"); + let d = app.ui.dialog.clone().unwrap(); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Dark"), Some(saved), "OK renames the group with its saved colors"); + } + + /// Without art, Save Changes with a Global Adjust gives the group the rows' new colors with the + /// adjustment, and OK gives it the same colors again: the adjustment applies to the rows' new + /// colors, not to the saved group. + #[test] + fn saving_a_group_without_art_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain").unwrap(), saved, "OK does not darken the group again"); + } + + /// With Limit to Library, Save Changes gives the group the library's nearest color to a row's + /// new color, as OK does, also when the rows were set without being snapped. + #[test] + fn saving_a_group_snaps_its_colors_to_the_library() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let names: Vec<_> = doc + .swatches + .iter() + .filter(|s| !s.is_reserved()) + .map(|s| s.name.clone()) + .chain(doc.swatch_groups.iter().map(|g| g.name.clone())) + .collect(); + app.run("swatch.delete", json!({"names": names})).unwrap(); + app.run("swatch.new", json!({"name": "Only Yellow", "color": "#ffff00"})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ffff00"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("limitTo".into(), json!("document")); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 250 250 10"); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ffff00".into()]), "the saved color is the library's"); + } + + /// Without art, Save Changes removes a removed color's swatch and adds a color added on the Edit + /// tab, and OK afterwards gives the group the same colors: it removes and adds nothing more. + #[test] + fn saving_a_group_without_art_with_added_and_removed_colors_keeps_them_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#00ff00") { + r["to"] = Value::Null; + } + } + // The added color's row was moved ahead of the others. + rs.insert(0, json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = ["#ff0000", "#0000ff", "#ffff00"].map(String::from).to_vec(); + assert_eq!(group_hex(&app, "Plain"), Some(want.clone()), "the save removes green and adds yellow"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(want), "OK gives the group the same colors"); + } + + /// With art: a group picked in the list reduces the art to a row per color of the group, which + /// become the rows' new colors, and the art previews them; the list draws beside the tabs and + /// hides with `groupStorage`. + #[test] + fn a_group_picked_in_the_list_recolors_the_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Warm", "colors": ["#ffff00", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Cool", "colors": ["#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + assert_eq!(fill_hex(&app, red), "#ff0000"); + // A button set with the group, before a frame, saves the rows the group gives the art. + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + set(&mut app, "group", json!("Warm")).unwrap(); + act(&mut app, &ctx, 0.1, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + let mut saved: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + saved.sort(); + assert_eq!((doc.swatch_groups.len(), saved), (n + 1, vec!["#00ff00".to_string(), "#ffff00".to_string()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(super::rows(d).len(), 2); + assert_eq!(d.str("groupName"), "Warm"); + let mut shown = [fill_hex(&app, red), fill_hex(&app, blue)]; + shown.sort(); + assert_eq!(shown, ["#00ff00", "#ffff00"], "the art previews the group's colors"); + // The name the preview gives the group being edited picks that group in the list. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Sunny")); + frame(&mut app, &ctx, 0.21, vec![], 0); + set(&mut app, "group", json!("Sunny")).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["group"], &d.fields[GROUP_LOADED], d.str("groupName")), (&json!("Warm"), &json!("Warm"), "Sunny".into())); + // A group the document has under that name is picked instead. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Cool")); + frame(&mut app, &ctx, 0.22, vec![], 0); + set(&mut app, "group", json!("Cool")).unwrap(); + frame(&mut app, &ctx, 0.23, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields[GROUP_LOADED], super::rows(d).len()), (&json!("Cool"), 1)); + set(&mut app, GROUP_STORAGE, json!(false)).unwrap(); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], false); + } } diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 2ed0d00e5f..b931e67c30 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -831,7 +831,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 af047a4cc2..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); } @@ -590,9 +622,10 @@ fn image_rows(ui: &mut egui::Ui, d: &mut Dialog, key: &str, title: &str) { ui.horizontal(|ui| { pick::(ui, d, &format!("{base}.downsample"), 150.0, |_| true); ui.label(tl!("to")); - number(ui, d, &format!("{base}.ppi"), " ppi", on); + let ppi = super::ppi_suffix(); + number(ui, d, &format!("{base}.ppi"), &ppi, on); ui.label(tl!("above")); - number(ui, d, &format!("{base}.abovePpi"), " ppi", on); + number(ui, d, &format!("{base}.abovePpi"), &ppi, on); }); ui.horizontal(|ui| { ui.label(tl!("Compression:")); @@ -656,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. @@ -711,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.")); } @@ -911,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/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 8f5e3b1093..f8baa7b7de 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -13,10 +13,22 @@ //! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer. //! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert. //! Stop ends the run and puts back everything it did. +//! +//! A script's file dialog (kind `scriptFiles`: `File.openDialog`, `File.saveDialog`, +//! `Folder.selectDialog` and the objects' `openDlg`, `saveDlg` and `selectDlg`) has the fields +//! `kind` (open, save or folder), `prompt` and `canAlways`, and takes `answer`: `once`, `always` +//! (only with `canAlways`), `deny` or `stop`. Only the person at the keyboard answers `once` or +//! `always`: from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input they are refused, and the +//! dialog stays open; `deny` and `stop` are taken from automation too. The paths it allows are the +//! ones Choose… picked in the host's file dialog, at most 2,048; `ui.dialog.set` cannot set them, +//! and the dialog's own fields change neither what it allows nor what it says it allows. Escape, +//! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny. +//! `selectDlg` opens the host's folder picker in its own folder. use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; use super::{DialogAction, DialogSpec}; @@ -32,6 +44,19 @@ pub const GROWTH_KIND: &str = "scriptGrowth"; pub const CLOSE_KIND: &str = "scriptClose"; /// The dialog kind of a script's `alert`, `confirm` and `prompt`. pub const NOTICE_KIND: &str = "scriptDialog"; +/// The dialog kind of a script's file dialogs. +pub const PICKER_KIND: &str = "scriptFiles"; + +pub(super) const PICKER_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Script File Access").into(), + body_with_actions: Some(picker_body), + confirm: picker_confirm, + ok: None, + inputs: |_| &["answer"], + min_width: 420.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec { heading: notice_heading, @@ -171,7 +196,7 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { - let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND); + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND); if app.ui.dialog.is_some() { return; } @@ -192,6 +217,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { if !app.session.script_running() { app.ui.dialog = None; } else if app.session.script_dialog().is_none() + && app.session.script_picker().is_none() && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); @@ -327,6 +353,192 @@ fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result = match p.kind { + PickerKind::Open if several => crate::picks::open_files(app, &pick), + PickerKind::Open => crate::picks::open(app, &pick).into_iter().collect(), + PickerKind::Save => crate::picks::save(app, &pick).into_iter().collect(), + // `selectDlg` starts in its folder; `Folder.selectDialog` gives none. + PickerKind::Folder => match p.start.clone() { + Some(start) => crate::picks::folder_at(app, &start).into_iter().collect(), + None => crate::picks::folder(app).into_iter().collect(), + }, + }; + if !chosen.is_empty() { + let mut paths = if several { std::mem::take(&mut app.script_picked) } else { Vec::new() }; + let mut seen: std::collections::HashSet = paths.iter().cloned().collect(); + for path in chosen { + if seen.contains(&path) { + continue; + } + if paths.len() >= MAX_ENTRIES { + app.script_picked_left_out = true; + break; + } + seen.insert(path.clone()); + paths.push(path); + } + app.script_picked = paths; + } + Ok(()) + }); + // Picking a path doesn't fail. + let _ = r; +} + +/// The dialog's prompt and the access it describes come from the request the run waits at, not +/// from the dialog's fields, so `ui.dialog.set` cannot change what the person reads. +fn picker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let t = Tokens::get(ui.ctx()); + let Some((kind, prompt)) = app.session.script_picker().map(|p| (p.kind, shown_text(&p.prompt, true))) else { return DialogAction::None }; + if !prompt.is_empty() { + egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| ui.label(&prompt)); + ui.add_space(8.0); + } + ui.label(picker_request(kind)); + ui.add_space(8.0); + let paths = app.script_picked.clone(); + ui.horizontal(|ui| { + if widgets::secondary_button(ui, tl!("Choose…")).clicked() { + choose(app, d); + } + ui.add_space(8.0); + if let [path] = paths.as_slice() { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + if paths.len() > 1 { + ui.add_space(4.0); + egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, |ui| { + for path in &paths { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + } + if app.script_picked_left_out { + ui.add_space(4.0); + ui.colored_label(t.error, crate::i18n::msg(PICKED_LEFT_OUT)); + } + ui.add_space(16.0); + let chosen = !app.script_picked.is_empty(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let mut answer = None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + if widgets::primary_button_enabled(ui, tl!("Allow Once"), chosen).clicked() { + answer = Some("once"); + } + ui.add_space(8.0); + if can_always { + if ui.add_enabled_ui(chosen, |ui| widgets::secondary_button(ui, tl!("Always Allow This Script"))).inner.clicked() { + answer = Some("always"); + } + ui.add_space(8.0); + } + if widgets::secondary_button(ui, tl!("Deny")).clicked() { + answer = Some("deny"); + } + // The row runs right to left: Stop goes at its left end. + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if widgets::secondary_button(ui, tl!("Stop")).clicked() { + answer = Some("stop"); + } + }); + }); + // Enter gives the dialog's default answer, Deny, as `ui.dialog.confirm` without an answer does, + // unless it goes to the button that has the keyboard focus (Choose…). + let unfocused = ui.ctx().memory(|m| m.focused().is_none()); + if answer.is_none() && unfocused && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + answer = Some("deny"); + } + let Some(answer) = answer else { return DialogAction::None }; + d.fields.insert("answer".into(), json!(answer)); + DialogAction::Confirm +} + +/// What the file dialog of `kind` asks the person to allow. +fn picker_request(kind: PickerKind) -> &'static str { + match kind { + PickerKind::Open => tl!("The script asks to read a file you choose."), + PickerKind::Save => tl!("The script asks to read and write a file you choose."), + PickerKind::Folder => tl!("The script asks to read and write a folder you choose, with everything in it."), + } +} + +/// The note the file dialog shows when the person picked more files than a script is given. +const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; + +/// Gives the running script the file dialog's `answer`, or Deny. +fn picker_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or("deny"); + give_pick(app, answer) +} + +/// Escape or Cancel: Deny. +pub(super) fn picker_cancel(app: &mut VectorcraftApp, _: &Dialog) { + let _ = give_pick(app, "deny"); +} + +/// Gives the running script `answer` with the paths Choose… picked. Only the person at the keyboard +/// allows access: Allow Once and Always Allow are refused, and the dialog stays open, while +/// automation sends the answer (a control or MCP request, or synthetic input) or opened the host's +/// file dialog; Deny and Stop are taken from anyone. +fn give_pick(app: &mut VectorcraftApp, answer: &str) -> Result { + let paths = app.script_picked.clone(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let given = match answer { + "stop" => None, + "deny" => Some(PickAnswer::Deny), + "once" | "always" if app.automation_asked() => return Err("Only the person at the keyboard can allow a script's file access".into()), + "once" | "always" if paths.is_empty() => return Err("choose a file or folder first, or deny".into()), + "always" if !can_always => return Err("this script's file access can be allowed only once".into()), + "once" => Some(PickAnswer::Allow { paths, always: false }), + "always" => Some(PickAnswer::Allow { paths, always: true }), + _ => return Err("`answer` for a script's file dialog must be one of: once, always, deny, stop".into()), + }; + app.script_picked.clear(); + app.script_picked_left_out = false; + match given { + None => { + app.session.script_request_stop(); + } + Some(a) => { + app.session.script_pick(a); + } + } + if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PICKER_KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) +} + fn answers_for(kind: &str) -> &'static str { match kind { "confirm" => "yes, no, stop", 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/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index 88838585ee..4257c15177 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -87,7 +87,7 @@ impl Strip { /// The open strip `d` moves to the level `cmd {auto: true}` picks for the selection, and the /// canvas previews it → {level}. pub fn auto(&self, app: &mut VectorcraftApp, mut d: Dialog) -> Result { - let _ = app.session.begin_interaction(self.label); + app.begin_interaction(self.label)?; let r = app.session.preview(self.cmd, &json!({ "auto": true })).map_err(|e| e.to_string())?; let level = r["level"].as_f64().unwrap_or(self.default_level); d.fields.insert("level".into(), json!(level)); 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("